This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: Update windows forms from another thread
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
I wrote this in response to a customer question today, and thought it might be interesting:
******
To update something on a form from another thread, you need to use Invoke() to get
to the right thread. If I have a method that's called through an EventHandler delegate,
it will look something like:
public void ButtonClick(object sender, EventArgs e)
{
// update the form here...
}
If this is called through a different thread, and it tries to update the code, bad
things may happen. So, you need to have a way to get there, and that's what Invoke()
does - it arranges for the code to be called on the right thread. The simplest thing
to do is to just use Invoke() to the same function, with a test to see if we're on
the right thread. Windows forms provides the function to do the testing...
public void ButtonClick(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(ButtonClick), new object[] {sender, e});
}
else
{
// update the form here...
}
}
That works well, though it is a bit ugly. When you move to the Compact Framework,
things get a bit weird. You can still use Invoke() on the compact framework, but it
has two strange restrictions:
1) You can't pass any parameters to the method, because Invoke() only has one parameter,
the delegate.
2) You need to call through an EventHandler delegate.
You can get around the first one by saving any parameters in a field before the Invoke(),
but it's a bit ugly. The second part is weird because EventHandler has two parameters,
but since you can't specify any parameter values, there's no way to use them.