Invoke 和 BeginInvoke 的真正涵义
来源:互联网 发布:arm7的寄存器数据宽度 编辑:程序博客网 时间:2024/05/22 01:49
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 线程负担的目的了。
而在那段更新树节点的代码中,其实唯一起作用的代码是:System.Threading.Thread.Sleep(100);,它使 UI 线程有了处理界面消息的机会,其实 数码幽灵 将问题复杂化了,只要以下的代码就可以很好的工作了。
private void button1_Click_(object sender, System.EventArgs e){ TreeNode tn; for(int i=0;i<100000;i++) { tn=new TreeNode (i.ToString()); this.treeView1.Nodes[0].Nodes.Add(tn); if (i%100 == 0) Application.DoEvents(); }}
- 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
- Go在谷歌:以软件工程为目的的语言设计
- oracle创建表空间
- 创业公司SOASTA:曾帮助伦敦奥运会官网进行云负载测试
- android下 gps的使用
- Ubuntu卸载内核的方法
- Invoke 和 BeginInvoke 的真正涵义
- 为Hi3531添加4串口支持
- ERP项目实施记录01
- Chapter 2. MATLAB数据及其运算
- AWD Format: About
- hibernate 的Configuration类
- Ruby on Rails学习笔记1
- 使用VS2012 的15个技巧
- FormatUtils java格式化 随笔