I have been playing around with methods of calling of calling a method safely in threadsafe manner in .net 2.0.
My treeview is populated from a call to a database on a separate thread;
Below is my attempt to use my InvokeFunction method ( shown below) …it works, but I was hoping that there was a nicer way to write this…any thoughts on this?
InvokeFunction(delegate() { TreeView1.Nodes.Clear(); });
delegate void FunctionDelegate();
private delegate void ThreadSafeProcess(FunctionDelegate func);
private void InvokeFunction(FunctionDelegate func)
{
if (this.InvokeRequired)
{
ThreadSafeProcess d = new ThreadSafeProcess(InvokeFunction);
this.Invoke(d, new object[] { func });
}
else
{
func();
}
}
BackgroundWorkeris a cleaner solution in .NET 2.0.It will create a thread for you and take care of synchronization.
You add
BackgroundWorkercomponent to you Form in the design mode.You subscribe to
DoWorkevent. The method subscribed to this will be execute in a background thread when you callbackgroundWorker.RunWorkerAsync()in your UI thread.When you need to interact with UI thread from your background thread you call
backgroundWorker.ReportProgress.This will trigger
ProgressChangedevent.ProgressChangedevent is always executed in UI thread.You can use
userStateparameter ofbackgroundWorker.ReportProgressto pass any data to UI thread. For example in your case the data that is needed to add newTreeViewnodes.You will actually add new nodes inside of
ProgressChangedevent handler.Here is the link to MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx.
Keep in mind you don’t have to use
percentProgressparameter of the methodReportProgressmethod. Although it is convenient when you have a progress bar to reflect background work progress.