C# 跨執行緒呼叫TextBox方法淺析
阿新 • • 發佈:2019-01-23
首先來看下面程式碼:
主執行緒:
delegate void SetTextCallback(string text); private void SetText(string text) { if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } private void BtnMainThread_Click(object sender, EventArgs e) //主執行緒呼叫textBox1 { this.textBox1.Text = "Main Thread"; } |
子執行緒:
private void BtnNewThread_Click(object sender, EventArgs e) //子執行緒呼叫textBox1 { this.demoThread = new Thread(new ThreadStart(this.NewThreadSet)); this.demoThread.Start(); } private void NewThreadSet() { this.SetText("New Thread"); } |
1.首先需要對“this.textBox1.InvokeRequired”返回值的解釋:
當主執行緒呼叫其所在的方法時返回“False”,
當子執行緒呼叫其所在的方法時返回“True”。
2.當單擊"主執行緒呼叫textBox1"時,
"this.textBox1.InvokeRequired"的返回值為"False",
直接執行"else"的程式碼,"textBox1"中顯示“Main Thread”;
3.當單擊"子執行緒呼叫textBox1"時,
"this.textBox1.InvokeRequired"的返回值為"True",
執行
“ SetTextCallback d = new SetTextCallback(SetText);”
“this.Invoke(d, new object[] { text });”
這兩句程式碼,其中Invoke的作用是“在擁有控制元件的基礎視窗控制代碼的執行緒上,用指定的引數列表執行指定委託。”:
a. “在擁有控制元件的基礎視窗控制代碼的執行緒上”就是指主執行緒,
b. “指定的引數列表”是指的引數“text”,
c. “指定委託”是指“SetText”方法。
這樣就很容易看出:
程式碼執行到“Invoke”後就會把子執行緒的引數“ New Thread ”交給主執行緒去執行“SetText”方法,此時由於是主執行緒呼叫SetText方法,所以this.textBox1.InvokeRequired的返回值為False,直接執行else的程式碼,textBox1中顯示“New Thread”。