在一个用于模拟局域网信使的C#程序中,我有一个回调函数用于beginreceive,在其中我需要在特定的文本框中显示接收到的文本。
this.textBox1.Text = sb.ToString();
但是这样做会出现“跨线程操作无效”错误。
我意识到我需要使用object.invoke方法,但您能否提供完整的代码来调用委托,因为当涉及到线程时,我仍然很幼稚。谢谢。
this.Invoke((MethodInvoker) delegate {
this.textBox1.Text = sb.ToString();
});
这里使用了C#的"匿名方法"和"捕获变量"功能来完成所有繁重的工作。在.NET 3.5中,你可能更喜欢使用Action
,但这并没有什么实质性的区别:
this.Invoke((Action) delegate {
this.textBox1.Text = sb.ToString();
});
void MyCallback(IAsyncResult result)
{
if (textBox1.InvokeRequired) {
textBox1.Invoke(new Action<IAsyncResult>(MyCallBack),new object[]{result});
return;
}
// your logic here
}