Thursday, February 15, 2007

Don't confuse Control.BeginInvoke() with Delegate.BeginInvoke()

In my last article I used the BeginInvoke() method to execute a delegate on the GUI thread.

Here is the definition of the delegate (this is just an example):

delegate void Invoker(string parameter);

And here you see where the delegate is used:

// Execute on the GUI thread this.BeginInvoke(new Invoker(SetTitleSafe), title);

Some people may confuse this with the BeginInvoke-method on a delegate, like this:

Invoker i = new Invoker(SetTitleSafe); // Execute on a threadpool thread i.BeginInvoke();

Note however that these are two completely different concepts!

Control.BeginInvoke is used to execute code on the GUI thread, while Delegate.BeginInvoke is used to execute code on a threadpool thread. For more information, click here.

One important difference is that when you invoked Control.BeginInvoke you are not obliged to call Control.EndInvoke. However, when you call Delegate.BeginInvoke you should also call Delegate.EndInvoke, otherwise you will have a memory leak!

This obligation to call EndInvoke may likely complicate your code. Mike Woodring has written a nice helper-class that will help you with this. Or you can also use Threadpool.QueueUserWorkItem (this is also used in the back by Delegate.BeginInvoke).

No comments: