C# 访问UI线程
采用SynchronizationContext的Post/Send方法更新
异步更新UI控件需要两步:
1. 是要获取UI线程的上下文
2. 调用post方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public 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(){
//执行设置控件代码
}
}使用控件自身的invoke/BeginInvoke方法
继承Control类的UI控件都可以使用Invoke方法异步更新
1
2
3
4
5
6
7
8
9
10
11
12private void button6_Click(object sender, EventArgs e)
{
Thread demoThread =new Thread(new ThreadStart(threadMethod));
demoThread.IsBackground = true;
demoThread.Start();//启动线程
}
void threadMethod()
{
Action<StringAsyncUIDelegate=delegate(string n){label1.Text=n;};
label1.Invoke(AsyncUIDelegate,new object[]{"修改后的label1文本"});
}