I haven’t done much multithreading before and now find the need to do some background work and keep the UI responsive. I have the following code.
data.ImportProgressChanged += new
DataAccess.ImportDelegate(data_ImportProgressChanged);
Thread importThread = new Thread(
new ThreadStart(data.ImportPeopleFromFAD));
importThread.IsBackground = true;
importThread.Start();
void data_ImportProgressChanged(int progress)
{
toolStripProgressBar.Value = progress;
}
//In my data object I have
public void ImportPeopleFromFAD()
{
ImportProgressChanged(someInt);
}
But the UI doesn’t get updated since the ImportProgressChanged() call is made on the background thread. In objective C I know you can use performSelectorOnMainThread and pass it a method to call using the main thread. What is the equivalent way of calling ImportProgressChanged() from the main thread?
(Assuming Windows Forms.) You can use
Control.InvokeorControl.BeginInvoke– but a cleaner way may be to useBackgroundWorkerto start with.In WPF you’d use a
Dispatcherinstead ofControl.Invoke, btw. See this WPF threading model guide for more details.EDIT: Personally I probably wouldn’t bother testing
InvokeRequiredfirst – I’d just callInvokeorBeginInvoke. If you’re already “on” the right thread it won’t do any significant harm.For progress bars, however,
BackgroundWorkeris definitely the way forward.