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
+4
A:
You need to push the work back onto the UI; luckily, it is easy:
this.Invoke((MethodInvoker) delegate {
this.textBox1.Text = sb.ToString();
});
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();
});
Marc Gravell
2009-03-29 09:56:55
+3
A:
You can use it in this way:
void MyCallback(IAsyncResult result)
{
if (textBox1.InvokeRequired) {
textBox1.Invoke(new Action<IAsyncResult>(MyCallBack),new object[]{result});
return;
}
// your logic here
}
Stormenet
2009-03-29 09:58:12