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 线程负担的目的了。
- Invoke 和 BeginInvoke 的真正涵义
- C# Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- C# Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- Invoke 和 BeginInvoke 的真正涵义
- C#中Invoke 和 BeginInvoke的涵义和区别
- Invoke和BeginInvoke的真正含义
- control 的invoke 和begininvoke
- Control的Invoke和BeginInvoke
- MPEG-2标准简介
- Linux Shell变量使用
- Filter Graph的事件交互机制
- 如何把一个CString转化为WCHAR*
- 一个算牌的概率问提。(组合)很有成就感!
- Invoke 和 BeginInvoke 的真正涵义
- 培养敏捷态度[转]
- U盘坏了
- Windows Mobile 开发环境搭建指南(摘自《Windows Mobile 手机应用开发》
- ArcView GIS 应用与开发技术(11)-空间分析
- 严重: Error listenerStart的解决办法---使用Spring时遇到的问题
- 2006年8月10日 22时24分魔兽搞笑记
- 2007年7月8日 0时23分离开了
- 数据库还原操作