谁能告诉我 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;
}
}
最佳答案
- 另一个线程调用SetText
- 因为它不是创建表单的线程,所以它需要
Invoke
。 this.Invoke
使用给定参数再次调用 SetText。还要检查 this- 现在 SetText 是从 UI 线程调用的,不需要 Invoke
- 在
else
block 中,我们确定文本已安全设置为线程
关于c# - 跨线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14704483/