1.首先通過按鍵創建子線程:
創建子線程,子線程調用changeText方法。
1 private void btnOK_Click(object sender, EventArgs e) 2 { 3 Thread th = new Thread(changeText); 4 th.Name = "new Thread!"; 5 th.IsBackground = true; 6 th.Start(); 7 }
2.子線程操作彈窗提示:
1 void changeText() 2 { 3 Thread.Sleep(3000); 4 MessageBox.Show("進入子線程:"+Thread.CurrentThread.Name); 5 }
效果圖:

3.子線程修改主線程控件
(1)錯誤的直接使用:
1 void changeText() 2 { 3 Thread.Sleep(3000); 4 textBox1.Text = "進入子線程!"; 5 }
效果圖:

(2)關閉跨線程的檢查:
1 CheckForIllegalCrossThreadCalls = false;
效果圖:

(3)對跨線程進行檢查
聲明委托:
注:參數類型是object型
1 public delegate void changeTextHandler(object str);
按鍵點擊調用方法修改控件:
注:參數不是在線程創建的時候寫入,是在start函數寫入!
1 private void btnOK_Click(object sender, EventArgs e) 2 { 3 Thread th = new Thread(changeText); 4 th.Name = "new Thread!"; 5 th.IsBackground = true; 6 th.Start("進入子線程!"); 7 }
修改控件的方法(帶一個參數):
1 void changeText(object str) 2 { 3 if (textBox1.InvokeRequired == true) 4 { 5 changeTextHandler ct = new changeTextHandler(changeText); 6 textBox1.Invoke(ct, new object[] { str }); 7 } 8 else
9 { 10 textBox1.Text = str.ToString(); 11 } 12 }
效果圖:

(4)使用MethodInvoker解決跨線程問題
- MethodInvoker是無參無返回值;
- Action是多參無返回;
- Func是多參又返回。
1 private void btnOK_Click(object sender, EventArgs e) 2 { 3 Thread th = new Thread(changeText); 4 th.Name = "new Thread!"; 5 th.IsBackground = true; 6 th.Start(); 7 }
調用對事件的處理方法:
1 void changeText() 2 { 3 Thread.Sleep(3000); 4 MethodInvoker ln = new MethodInvoker(change); 5 this.BeginInvoke(ln); 6 }
調用對控件的修改方法:
1 void change() 2 { 3 textBox1.Text = "進入子線程!"; 4 }
效果圖:

