Reputation: 16685
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
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
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
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
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
Reputation: 153
You should check BackgroundWorker class. It supports progress and handles communication between threads properly.
Upvotes: 2