任何人都可以告诉我if和else语句在这个函数中是如何相关的。我正在从另一个线程向GUI线程显示文本。什么是执行的顺序或方式。其他声明是否必要?跨线程操作
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,因此您可以调用该方法。如果没有'else',外部线程会在调用方法后立即尝试更改GUI(导致前面提到的崩溃)。 'InvokeRequired'检查对象是否属于当前线程,基本上这意味着'this.textBox7.Text = text;'永远不会在'textBox7'所属的线程之外的任何线程上运行。 – Nolonar