一、背景
在C#中,由於使用線程和調用UI的線程屬於兩個不同的線程,如果在線程中直接設置UI元素的屬性,此時就會出現跨線程錯誤。
二、問題解決方法
- 使用控件自帶的Invoke或者BeginInvoke方法。
ThreadPool.QueueUserWorkItem(ar => { this.button1.Invoke(new Action(() => { this.button1.Text = "aa"; })); });
- 使用線程的同步上下文 SynchronizationContext
private SynchronizationContext _syncContext = SynchronizationContext.Current; private void button1_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(ar => { _syncContext.Post(p => { this.button1.Text = "aa"; }, null); }); }