C#跨线程操作错误

3
在一个用于模拟局域网信使的C#程序中,我有一个回调函数用于beginreceive,在其中我需要在特定的文本框中显示接收到的文本。 this.textBox1.Text = sb.ToString(); 但是这样做会出现“跨线程操作无效”错误。 我意识到我需要使用object.invoke方法,但您能否提供完整的代码来调用委托,因为当涉及到线程时,我仍然很幼稚。谢谢。
2个回答

8
你需要将工作推回到用户界面;幸运的是,这很容易实现:
this.Invoke((MethodInvoker) delegate {
    this.textBox1.Text = sb.ToString();
});

这里使用了C#的"匿名方法"和"捕获变量"功能来完成所有繁重的工作。在.NET 3.5中,你可能更喜欢使用Action,但这并没有什么实质性的区别:

this.Invoke((Action) delegate {
    this.textBox1.Text = sb.ToString();
});

3
你可以这样使用它:
void MyCallback(IAsyncResult result)
{
if (textBox1.InvokeRequired) {
    textBox1.Invoke(new Action<IAsyncResult>(MyCallBack),new object[]{result});
    return;
}
// your logic here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接