Every programmer that has used multi-threaded programming knows the problem that you’ll run into when you try to access properties or methods of a control from within a thread other than the control was created on. To solve this problem you have to check wether an invoke is required and if so call the invoke method. Calling this invoke method is ok when you want to call a method or function on the control, but when you have to set some property you’ll need delegates. So you need to declare a delegate signature and provide an implementation for the delegate. At this point you can call the invoke method on the control passing the delegate and possible arguments.
In C# 2.0 you can now facilitate this further by using anonymous methods. These will allow you to pass a code block as a delegate parameter. It also allows for lesser code because you don’t need to write any named methods anymore.
Below you can see the code to set a Text propery on a TextBox control. The anonymous method is marked in bold.
delegate void setresponse(string envelope);
private void button1_Click(object sender, EventArgs e)
{
if (txtResponse.InvokeRequired)
{
setresponse settext = delegate(string envelope) { txtResponse.Text =
envelope; };
txtResponse.Invoke(settext, new object[] { “Hello !” });
}
else
{
txtResponse.Text = “Hello !”
}
}
As you can see there are 3 steps to take into account:
- declare a delegate signature (delegate void setresponse(string envelope);)
- check to see if an invoke is required (txtResponse.InvokeRequired)
- create an anonymous method and call the delegate.
