首先来看下面代码:
主线程:
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”。