SYSK 42: A must-read article on BackgroundWorker class


I was going to write a post on the different ways to execute code asynchronously in .NET, the pros and cons.  You know, BeginInvoke, QueueUserWorkItem, the new BackgroundWorker class, the direct thread creation…  Before doing that, I wanted to check out if somebody has already done similar posting, and I came across this jewel from Julia Lerman with Michael Cambell’s (as a feedback).   Strongly recommended!  You can find it at http://blog.ziffdavis.com/devlife/archive/2005/12/21/39532.aspx.


 


Summary: it may be possible that RunWorkerCompleted event is fired on a thread different from the UI thread.  To avoid exceptions when touching UI controls, use InvokeRequired and Invoke methods, if necessary. 


Comments (3)

  1. tzagotta says:

    If I understand correctly, the issue she brought up was not resolved??

  2. irenak says:

    The solution is to use InvokeRequired check, and call Invoke method, if necessary as described in http://msdn2.microsoft.com/en-us/library/ms171728.aspx

  3. Julie Lerman says:

    Although doing the InvokeRequired check and invoking (if required) did the trick, the real problem brought up by my post is that the UI thread behavior that I was experiencing by calling the background worker programatically and NOT from the click of a UI control, was different than what the documentation suggests. It took me a lot of experimentation to figure out what I was doing "wrong" and WHY the invoke was necessary at all.