To Invoke or not to Invoke? That is the Question!

Yesterday I was having a problem with my UI on my smart client application.  I’m using the offline data block from the MS Patterns and Practices group.  It took awhile to learn how to use this, but now that I am I really like it.  It uses a separate thread to do the data requests.  Well, as most applications would I wanted that thread to update a progress bar on my UI to tell the user how many requests where in the queue and when they where completed.

This sounds like it should be easy, but hopefully most of you know that a separate thread cannot update a UI element on the main GUI thread.  This article talks about why and how to do it using the Invoke() method.  I was using the Invoke() method and everything was running fine at first.  However, after I started testing the application started to deadlock\freeze.  I put lock statements all around my code to try and avoid the problem to no avail.

Finally I ran across this post from Kristof Verbiest which explained my problem.  The Invoke() method IS NOT an asynchronous call.  The code will wait for the method called within the Invoke() to complete before it moves on.  So, what was happening was my main thread was waiting for the Invoke() and also calling the thread to do another request.  This caused the deadlock.  The post from Kristof explained that the BeginInvoke() method IS an asynchronous and will allow the code to continue.  By changing my Invoke() calls to BeginInvoke() I fixed my problem.  Thanks Kristof!

So the answer is to not Invoke(), but to BeginInvoke()…

Posted in |

2 comments:

  1. Anonymous Says:

    Thanks for that Ben. I think that this may come in very handy in one of my current projects!

  2. Kristof Says:

    I'm glad I could help. Thanks for the link!