Krimson
Krimson

Reputation: 7664

Run a method and update progressbar using tpl

I have the following class:

class MyClass
{
    public void timeConsumingCode(){
        for(int i=0; i<100; i++)
        {
            Threading.Thread.Sleep(1000);
        }
    }
}

and then i have my Form1 code:

private void btn_RunTimeConsumingCode_Click(object sender, EventArgs e)
{
    Task loadMasterFile = Task.Factory.StartNew(() => 
    { 
        MyClass myclass = new MyClass();
        myClass.timeConsumingCode();
    });
}

till now everything works fine. However I added a progressbar on the form and I want to update it based on the value of i ie. if i=34 then 34% done.

I could invoke the progress bar property from the timeConsumingCode() to change the value but i want to keep the class as separate as possible from the form so that in the future it can be ported to other apps.

Is there a way that I can change the value of my progressbar without having to make the MyClass depended on the form1?

I hope I was clear enough

Upvotes: 2

Views: 1353

Answers (1)

SWeko
SWeko

Reputation: 30902

The TPL in the .net 4.5 framework has an IProgress<T> interface that is implemented as Progress<T>. In your case, as you'll need a single number as a progress report you could use a Progress<int> instance and attach an event handler to its ProgressChanged event, along these lines:

private void btn_RunTimeConsumingCode_Click(object sender, EventArgs e)
{
    IProgress<int> progress = new Progress<int>(p => {...ui handling code ...});

    Task loadMasterFile = Task.Factory.StartNew(() => 
    { 
      MyClass myclass = new MyClass();
      myClass.timeConsumingCode(progress);
    });
}

coupled with calling

progress.Report(someNumber);

at the appropriate places in the MyClass.timeConsumingCode method.

Of course, the event handler (here specified as a constructor argument) is called asynchronously.

Upvotes: 6

Related Questions