Invoke 和 BeginInvoke 的真正涵义

来源:互联网 发布:linux怎么启动nginx 编辑:程序博客网 时间:2024/05/01 08:54

BeginInvoke 方法真的是新开一个线程进行异步调用吗?

参考以下代码:

public delegate void treeinvoke();private void UpdateTreeView(){      MessageBox.Show(System.Threading.Thread.CurrentThread.Name);}private void button1_Click(object sender, System.EventArgs e){      System.Threading.Thread.CurrentThread.Name = "UIThread";      treeView1.BeginInvoke(new treeinvoke(UpdateTreeView));}

看看运行结果,弹出的对话框中显示的是 UIThread,这说明 BeginInvoke 所调用的委托根本就是在 UI 线程中执行的。

既然是在 UI 线程中执行,又何来“异步执行”一说呢?

我们再看看下面的代码:

public delegate void treeinvoke();private void UpdateTreeView(){      MessageBox.Show(Thread.CurrentThread.Name);}private void button1_Click(object sender, System.EventArgs e){      Thread.CurrentThread.Name = "UIThread";      Thread th = new Thread(new ThreadStart(StartThread));      th.Start();}private void StartThread(){      Thread.CurrentThread.Name = "Work Thread";      treeView1.BeginInvoke(new treeinvoke(UpdateTreeView));}

再看看运行结果,弹出的对话框中显示的还是 UIThread,这说明什么?这说明 BeginInvoke 方法所调用的委托无论如何都是在 UI 线程中执行的。

那 BeginInvoke 究竟有什么用呢?

在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误的做法,具体的原因可以在看完我的这篇之后看看这篇:在多线程中如何调用Winform,如果你是大牛的话就不要看我这篇了,直接看那篇吧,反正那篇文章我没怎么看懂。

Invoke 和 BeginInvoke 就是为了解决这个问题而出现的,使你在多线程中安全的更新界面显示。

正确的做法是将工作线程中涉及更新界面的代码封装为一个方法,通过 Invoke 或者 BeginInvoke 去调用,两者的区别就是一个导致工作线程等待,而另外一个则不会。

而所谓的“一面响应操作,一面添加节点”永远只能是相对的,使 UI 线程的负担不至于太大而以,因为界面的正确更新始终要通过 UI 线程去做,我们要做的事情是在工作线程中包揽大部分的运算,而将对纯粹的界面更新放到 UI 线程中去做,这样也就达到了减轻 UI 线程负担的目的了。