How do I call a function in a threadsafe manner

纵然是瞬间 提交于 2020-01-24 19:39:08

问题


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();
  }
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5849120/how-do-i-call-a-function-in-a-threadsafe-manner

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!