Problem with BackgroundWorker and COM interop RRS feed

  • Question

  • I am trying to use BackgroundWorker to do a lengthy operation that requires UI updates (progress bar). The code in this lengthy operation uses two COM dlls. Without using the backgroundWorker, I tested the code and it was running fine with COM interop. When I added the backgroundWorker then the problems started. One of the dlls was working fine, I could create and object and call its methods. But the other was not working. In comparing the two COM dlls, I  noticed that the one that was working had ThreadingModel set to Apartment while the one that was not had ThreadingModel set to 'both'. I did a test to see if that made a difference and changed that one from 'both' to Apartment and then it worked. Can anyone please tell me why this makes a difference? Isn't the value 'both' support both STA and MTA? Then why does it have to be STA (Apartment) in order for it to work with BackgroundWorker?

    Monday, October 6, 2008 1:35 PM


  • > Isn't the value 'both' support both STA and MTA?

    Yes, but it is not unheard of for components to implement this incorrectly.

    BackgroundWorker uses the .NET thread pool.  Alternatively, you can create the thread manually via System.Threading.Thread if you need to control its COM threading via Thread.SetApartmentState.  For example, to set it to ApartmentState.STA as you apparently need in your case.
    • Marked as answer by Zhi-Xin Ye Friday, October 10, 2008 11:56 AM
    Monday, October 6, 2008 11:17 PM