i know that a requirement of COM that every thread call CoInitialize
before interacting with the COM system.
.NET exposes some items that internally operate on threads, e.g.:
ThreadPool
threads- asychronous delegates (which use thread pool threads)
BackgroundWorker
class (which use asychronous delegates (which use thread pool threads))- the garbage collector
- and more! (i.e. e.g.)
If i am going to be interacting with a COM object from a thread, do i need to call CoInitialize
first?
i ask because there may be some more magic that automagically calls it for me - i don't know.
Bonus Reading
Managed and Unmanaged Threading
For interoperability, the common language runtime creates and initializes an apartment when calling a COM object. A managed thread can create and enter a single-threaded apartment (STA) that contains only one thread, or a multi-threaded apartment (MTA) that contains one or more threads. When a COM apartment and a thread-generated apartment are compatible, COM allows the calling thread to make calls directly to the COM object. If the apartments are incompatible, COM creates a compatible apartment and marshals all calls through a proxy in the new apartment.
The runtime calls CoInitializeEx to initialize the COM apartment as either an MTA or an STA apartment.
Update Two:
Looks like you should not use COM from any kind of thread that .NET can provide:
The Managed Thread Pool
There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:
You require a foreground thread.
You require a thread to have a particular priority.
You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.
You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.
You need to have a stable identity associated with the thread, or to dedicate a thread to a task.
Update Three:
Looks like you can set the threading model of unmanged threads:
Managed and Unmanaged Threading in Microsoft Windows
A managed thread can be marked to indicate that it will host a single-threaded or multithreaded apartment. The GetApartmentState, SetApartmentState, and TrySetApartmentState methods of the Thread class return and assign the apartment state of a thread. If the state has not been set, GetApartmentState returns ApartmentState.Unknown.
The property can be set only when the thread is in the ThreadState.Unstarted state; it can be set only once for a thread.
If the apartment state is not set before the thread is started, the thread is initialized as a multithreaded apartment (MTA).
Lot of conflicting information.
Which is why we'll use whatever the guy on Stackoverflow said as the true answer.