有人能告诉我这个函数中的if和else语句有什么关系吗?我正在将来自另一个线程的文本显示到GUI线程中。执行的顺序或方式是什么?else语句是否必要?
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox7.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox7.Text = text;
}
}
else
,程序很可能会崩溃,因为您无法从外部线程更改GUI。既然您需要更改GUI,那么您应该使用Invoke
方法。如果没有else
,外部线程将在调用方法后尝试立即更改GUI(导致我之前提到的崩溃)。InvokeRequired
检查对象是否属于当前线程,基本上意味着this.textBox7.Text = text;
永远不会在除textBox7
所属的线程之外的任何线程上运行。 - Nolonar