private delegate void SetTextCallback(string text);
//在给textBox1.text赋值的地方调用以下方法即可
private void SetText(string text)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
//在给textBox1.text赋值的地方调用以下方法即可
private void SetText(string text)
{
// InvokeRequired需要比较调用线程ID和创建线程ID
// 如果它们不相同则返回true
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
本文介绍了一种在不同线程间安全更新Windows Forms中TextBox文本的方法。通过使用Delegate和Invoke方法确保了UI线程和后台线程之间的同步,避免了跨线程访问异常。
314

被折叠的 条评论
为什么被折叠?



