Friday, March 21, 2008

 

More on Control.BeginInvoke()

By now, everyone knows you use Control.BeginInvoke() to asynchronously execute a delegate on a the main UI thread, right? But, what happens if you call Control.BeginInvoke() while already on the UI thread?

The answer is simple: it does the same thing -- it asynchronously invokes the delegate on the main UI thread.

Huh? What does that mean if you are already on the UI thread?

If you are already on the UI thread, you can use Control.BeginInvoke() to queue a delegate to be executed on the main UI thread. It is added to the end of everything else that is already queue to be processed on the UI thread. For example, consider the example below.


private void Button_Click(
object sender,
EventArgs e)
{
_label.Text = "1";
BeginInvoke( new MethodInvoker( delegate() { _label.Text = "2"; } ));
_label.Text = "3";
}
 

What would you expect _label.Text to be? After setting it to "1" its value is "1". After the BeginInvoke() its value is still "1". After setting it to "3" it's value is "3". Sometime after Button_Click has returned, the anonymous method will run and _label.Text will change to "2".

So are there really any reasons why you would want to use this? Sure, but I don't have time to get into that now. Perhaps I will post about them in the future.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]