Everybody know how nice Task can be to work with, but did you know there is actually a interface for using a progressbar. I will show you how to use it and how to implement it and make use of it.

First of we start with write a class i called it ProgressClass with a int this will contain our reported progress. You can extend this class to contain anything you like that has todo with the progress reporting for example maybe you want to set Max value to your progressbar you could do this with an extra field in ProgressClass if you like to. But lets focus on reporting the progress only.

public class ProgressClass
{
     public int Progress { get; set; }
}

next up we need code for our progress and in C# there is already a class for this under System namespace called Progress that has an EventHandler called ProgressChanged that is what we need. Lets take a look at the example code:

private void Init()
{
var progress = new Progress<ProgressClass>();
progress.ProgressChanged += Progress_Changed;
StartTask(progress);
}

private void StartTask(IProgress<ProgressClass> progress)
{
    Task myTask = Task.Run(() =>
    {
        try
        {
                     for (int i = 0; i < 100; i++)
                     {
                        progress.Report(new ProgressClass { Progress = i+1 });
                        Thread.Sleep(100);
                     }
        }
        catch (Exception ex)
        {
            //Handle Exceptions!
        }
    });
}

private void Progress_Changed(object sender, ProgressClass e)
{
     MyProgressBar.Value = e.Progress;
}

So this is a very easy implementation to use a Progressbar for your .net application.

Have a nice weekened