How do I call a function in a threadsafe manner
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(InvokeFuncti开发者_运维百科on);
this.Invoke(d, new object[] { func });
}
else
{
func();
}
}
BackgroundWorker
is a cleaner solution in .NET 2.0.
It will create a thread for you and take care of synchronization.
You add BackgroundWorker
component to you Form in the design mode.
You subscribe to DoWork
event. The method subscribed to this will be execute in a background thread when you call backgroundWorker.RunWorkerAsync()
in your UI thread.
When you need to interact with UI thread from your background thread you call backgroundWorker.ReportProgress
.
This will trigger ProgressChanged
event. ProgressChanged
event is always executed in UI thread.
You can use userState
parameter of backgroundWorker.ReportProgress
to pass any data to UI thread. For example in your case the data that is needed to add new TreeView
nodes.
You will actually add new nodes inside of ProgressChanged
event 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 percentProgress
parameter of the method ReportProgress
method. Although it is convenient when you have a progress bar to reflect background work progress.
You dont have to worry abbout thread safety unless you share some state. Functions always receive their parameters on the stack and stack is local for each thread. So functions are not your problem. Instead focus on the state. "TreeView1" objects is a candidate to worry about.
精彩评论