【发布时间】:2013-02-05 09:49:51
【问题描述】:
谁能告诉我 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所属线程之外的任何线程上运行。
标签: c# multithreading