Multi-threading in .NET and COM objects

Some things I learned about using COM objects in multi-threaded managed applications:
  • RCW (runtime callable wrapper) takes care of calling COM object from the correct thread, even if COM object can’t be called from multiple threads (i.e. is apartment threaded). So: it is ok to call COM objects from multiple .NET threads.
  • However, you might run into problems if you create a COM object on a background thread and the background thread exits while the COM object stays in place. We solved this problem by using Invoke if we have to create a COM object in a background thread. This causes it to be created in the main thread which stays around.
  • Yet another issue are COM objects that are returned from a COM object, e.g. by a factory class. If the factory method gets called from the background thread the returned COM object seems to get a different RCW (runtime callable wrapper) than if it gets called from the main thread. This also causes problems when the background thread quits. The workaround for this problem was that we use a thread pool thread (or don’t quit the thread when the task is done).
  • The clipboard can only be accessed from STA threads.
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s