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.

Thursday, March 20, 2008

 

TimL on C#.NET has moved!

I have successfully moved http://csharp.timl.net to http://timl.net.

Wednesday, March 19, 2008

 

TimL on C#.NET is moving!

Sometime over the next few days, I will be moving my C# blog from http://csharp.timl.net to simply http://timl.net. I don't know for sure if it will affect anybody that subscribes to the feed, but I don't think it will. Never-the-less, I just thought I'd post this message incase any readers run into problems.

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

Subscribe to Posts [Atom]