Dev blog

C# Developer and a Geek

How too use Tasks and progressbar in .net

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.

1
2
3
4
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 crap)
        {
            //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


Lämna ett svar