3.子線程修改主線程控件
(1)錯誤的直接使用:
1 void changeText() 2 { 3 Thread.Sleep(3000); 4 textBox1.Text = "進入子線程!"; 5 }
效果圖:
(2)關閉跨線程的檢查:
1 CheckForIllegalCrossThreadCalls = false;
效果圖:
注:參數類型是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 }
效果圖:
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 }
效果圖:
菜鳥一枚,但有一顆不斷進取的心; 興趣所至,相信自己終會成功!!!!! 加油,imstrive