To Invoke or not to Invoke (i.e., to BeginInvoke)

Just a little something I learned recently that I thought we could all benefit from knowing:

To run some code that updates the GUI from a non-GUI thread, I think we’re all familiar by now that you need to use Control.Invoke. But actually, there is an alternative to Invoke that I believe to be highly superior in most cases: Control.BeginInvoke. Both of these methods do the same thing — send a message to the UI thread to run the specified code — but there’s an important difference: Invoke blocks, BeginInvoke doesn’t. In other words, if you call Invoke, the code will not progress past that point until the GUI has executed whatever method you invoked. BeginInvoke will continue.

This might not seem like a big deal, but it actually kind of is, under certain circumstances. Namely, Invoke can create a deadlock (i.e. totally freeze the application) if you have some OTHER code running on the GUI thread that is blocking, for whatever reason. For instance, say I have two threads, A (the GUI thread) and B. B calls Invoke on some method. Meanwhile, A has called a function which blocks until a certain condition is met. Problem is, what if this condition will not be met until some code runs on thread B? At this point, the application will just hang indefinitely because A is waiting for B and B is waiting for A.

The moral of this story is to try and use BeginInvoke where possible. Now, it’s conceivable you might have some code that needs to use Invoke for one reason or another (after all, if it were ALWAYS the wrong way to go, the method wouldn’t exist); but in these cases, just be especially careful to watch out for scenarios where deadlock might occur.

That’s all I got.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: