Paul Michaels
Paul Michaels

Reputation: 16685

Updating UI while running task

I have the following code:

        progressBar1.Minimum = 0;
        progressBar1.Maximum = Results.Count;

        foreach (MyClass cls in Results)
        {                
              progressBar1.Value += 1;

              // Go to DB and get large quantity of data
              cls.GetHistoryData();

        }

What I’d like to do is shift the processing to another thread so that progressBar1 updates correctly. I’ve found an article that implies that I should be able to use the Invoke method on the progress bar, but there doesn’t appear to be one.

Upvotes: 0

Views: 664

Answers (5)

bitbonk
bitbonk

Reputation: 49599

If you bind the progressbar to a data property you do not need to switch the thread context manually. The WPF binding engine will do this automatically for you.

<ProgressBar Value={Binding Progress} />

And then in your thread:

foreach (MyClass cls in Results)
{                
      // databinding will automatically marshal to UI thread
      this.Progress++;
      cls.GetHistoryData();
}

In most cases this is much cleaner and less error prone than marshalling on your own using Dispatcher.Invoke or BackgroundWorker

Upvotes: 2

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158289

The article you link to is a winforms example, but you are making a WPF application. In your case, you should look into using the Dispatcher class instead, that you get through the Dispatcher property of the control.

Upvotes: 0

Dean Chalk
Dean Chalk

Reputation: 20451

try this

progressBar1.Minimum = 0;
progressBar1.Maximum = Results.Count;

foreach (MyClass cls in Results)
{
    ThreadPool.QueueUserWorkItem((o) =>
             {
                 progressBar1.Dispatcher.BeginInvoke(
                     (Action) (() => progressBar1.Value += 1));
                 cls.GetHistoryData();
             });
}

Upvotes: 0

Darren Young
Darren Young

Reputation: 11090

You would start a new thread as such:

Thread t1 = new Thread(methodnametocall);
   t1.start();

void methodnametocall()
{
   this.Invoke((MethodInvoker)delegate
   {

        control to update;
    }
});

Upvotes: 0

peo
peo

Reputation: 153

You should check BackgroundWorker class. It supports progress and handles communication between threads properly.

Upvotes: 2

Related Questions