在C#中,因爲使用線程和調用UI的線程屬於兩個不一樣的線程,若是在線程中直接設置UI元素的屬性,此時就會出現跨線程錯誤。this
ThreadPool.QueueUserWorkItem(ar => { this.button1.Invoke(new Action(() => { this.button1.Text = "aa"; })); });
private SynchronizationContext _syncContext = SynchronizationContext.Current; private void button1_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(ar => { _syncContext.Post(p => { this.button1.Text = "aa"; }, null); }); }