如何以线程安全的方式调用函数 [英] How do I call a function in a threadsafe manner

查看:97
本文介绍了如何以线程安全的方式调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究在.net 2.0中以线程安全方式安全地调用方法的调用方法。

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;

以下是我尝试使用我的InvokeFunction方法的方法(如下所示)...它可以工作,但是我希望有一种更好的方法写这个...对此有什么想法吗?

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


推荐答案

BackgroundWorker 是.NET 2.0中的一种更干净的解决方案。
它会为您创建一个线程并负责同步。

BackgroundWorker is a cleaner solution in .NET 2.0. It will create a thread for you and take care of synchronization.

您将 BackgroundWorker 组件添加到您在设计模式下窗体。
您订阅了 DoWork 事件。当您在UI线程中调用 backgroundWorker.RunWorkerAsync()时,将在后台线程中执行预订的方法。

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.

需要从后台线程与UI线程进行交互时,请调用 backgroundWorker.ReportProgress
这将触发 ProgressChanged 事件。 ProgressChanged 事件始终在UI线程中执行。
您可以使用 backgroundWorker.ReportProgress userState 参数将任何数据传递到UI线程。例如,在您的情况下,添加新的 TreeView 节点所需的数据。
您实际上将在 ProgressChanged 事件处理程序内添加新节点。

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.

以下是MSDN的链接: http://msdn.microsoft.com/en-us/ library / system.componentmodel.backgroundworker.aspx

Here is the link to MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx.

请记住,您不必使用 percentProgress ReportProgress 方法的$ c>参数。虽然当您有一个进度条来反映后台工作进度时很方便。

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.

这篇关于如何以线程安全的方式调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆