C# 跨線程訪問UI線程控件
在C#中,由於使用線程和調用UI的線程屬於兩個不同的線程,如果在線程中直接設置UI元素的屬性,此時就會出現跨線程錯誤。
下面介紹兩種解決方案
第一種:使用控件自帶的Invoke或者BeginInvoke方法。
Task.Factory.StartNew(() => { this.button1.Invoke(new Action(() => { this.button1.Text = "hello world"; })); });
第二種:使用線程的同步上下文 SynchronizationContext
private SynchronizationContext _syncContext = SynchronizationContext.Current; private void button1_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => { _syncContext.Post(p => { this.button1.Text = "hello world"; }, null); }); }
以上兩種方式,均可實現跨線程訪問UI線程控件,且用且珍惜;