Invoke的用法
来源:互联网 发布:壁纸知乎 编辑:程序博客网 时间:2024/06/05 23:55
Invoke的用法(C#)
在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误的做法,Invoke 和 BeginInvoke 就是为了解决这个问题而出现的,使你在多线程中安全的更新界面显示。
正确的做法是将工作线程中涉及更新界面的代码封装为一个方法,通过 Invoke 或者 BeginInvoke 去调用,两者的区别就是一个导致工作线程等待,而另外一个则不会。
而所谓的“一面响应操作,一面添加节点”永远只能是相对的,使 UI 线程的负担不至于太大而已,因为界面的正确更新始终要通过 UI 线程去做,我们要做的事情是在工作线程中包揽大部分的运算,而将对纯粹的界面更新放到 UI 线程中去做,这样也就达到了减轻 UI 线程负担的目的了。
举个简单例子说明下使用方法,比如你在启动一个线程,在线程的方法中想更新窗体中的一个TextBox
using System.Threading;namespace test{ public partial class Form1 : Form { public delegate void MyInvoke(string str1,string str2); public Form1() { InitializeComponent(); } public void DoWork() { MyInvoke mi = new MyInvoke(UpdateForm); this.BeginInvoke(mi, new Object[] {"我是文本框","haha"}); } public void UpdateForm(string param1,string parm2) { this.textBox1.Text = param1+parm2; } private void button1_Click(object sender, EventArgs e) { Thread thread = new Thread(new ThreadStart(DoWork)); thread.Start(); } }}.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }
- Invoke的用法(C#)
- Invoke的用法
- Invoke的用法
- spring的invoke用法
- Invoke的用法
- 引用 Invoke的用法(C#)
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- C#中Invoke的用法
- Unity Invoke的另类用法
- C#中Invoke的用法
- C#中Invoke的用法
- Invoke 用法
- HttpSendRequest超时问题解决
- solaris上配置DNS客户端
- AD用户管理
- 学习过程
- offsetTop.offsetLeft,offsetWidth,offsetHeight,offsetParent,scrollTop,scrollLeft,scrollWidth,scrollHeight区别
- Invoke的用法
- String Function
- DBA 工作清单
- kernel 打补丁
- Brook+ Programming
- 追求
- tr命令使用
- Spring配置文件总结
- SQL学习笔记