C#跨线程操作错误 [英] C# cross thread operation error
问题描述
在用于模拟局域网信使C#程序,我对beginreceive一个回调函数,我需要显示在一个特定的文本框.. $ B $收到b this.textBox1.Text = sb.ToString()的文本;
然而在这样做,我得到一个跨线程操作无效错误。
我也知道我需要使用object.invoke方法,但可以ü请您提供完整的代码来调用一个委托,因为我还是幼稚的,当涉及到threading.Thank你
In a c# program for simulating a lan messenger, i have a callback function for beginreceive where i need to display the text received in a particular textbox.. this.textBox1.Text = sb.ToString(); However on doing so, I am getting a cross-thread operation not valid error. I do realize that i need to use the object.invoke method but could u please provide me with the complete code to invoke a delegate because am still naive when it comes to threading.Thank you
推荐答案
您需要按工作放回UI;幸运的是,它很容易:
You need to push the work back onto the UI; luckily, it is easy:
this.Invoke((MethodInvoker) delegate {
this.textBox1.Text = sb.ToString();
});
这使用匿名方法和俘获变量的C#的特征来完成所有的繁重。在.NET 3.5中,你可能更愿意使用动作
,但是这使得没有真正的区别:
This uses the "anonymous method" and "captured variables" features of C# to do all the heavy lifting. In .NET 3.5, you may prefer to use Action
, but that makes no real difference:
this.Invoke((Action) delegate {
this.textBox1.Text = sb.ToString();
});
这篇关于C#跨线程操作错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!