异步更新UI控件需要两步:
1. 是要获取UI线程的上下文
2. 调用post方法
public class ChangeUI //处在另一个线程 { SynchronizationContext _syncContext = null; publc ChangeUI(){ _syncContext = SynchronizationContext.Current; } public update(){ Thread demoThread =new Thread(new ThreadStart(threadMethod)); demoThread.Start();//启动线程 } private void threadMethod() { syncContext.Post(changeControl, "修改后的文本");//子线程中通过UI线程上下文更新UI } prviate void changeControl(){ //执行设置控件代码 } }
继承Control类的UI控件都可以使用Invoke方法异步更新
private void button6_Click(object sender, EventArgs e) { Thread demoThread =new Thread(new ThreadStart(threadMethod)); demoThread.IsBackground = true; demoThread.Start();//启动线程 } void threadMethod() { Action<String> AsyncUIDelegate=delegate(string n){label1.Text=n;}; label1.Invoke(AsyncUIDelegate,new object[]{"修改后的label1文本"}); }