.NET Framework - CoInitialize in C# ?

Asked By Urs Wigger on 05-Apr-07 09:35 AM
Hi,

I wanted to instantiate a STA COM component twice, once in the main
thread and once in a secondary thread. All worked fine for the main
thread, but for the secondary thread, I got 'Query Interface failed'
errors when trying to access COM methods.
I once had the same problem in a C++ application. The solution there was
to call CoInitialize() for each thread. So I tried the same in C#; I
added the following code to my worker thread class:

[DllImport("ole32.dll")]
static extern int CoInitialize(IntPtr pvReserved);

And then called 'CoInitialize((System.IntPtr)null)'
in the worker thread function, before instantiating the 2nd COM object.
AND IT WORKED!

Questions:
- Is this allowed?
- Is this correct?
- Isn't there a pendant for CoInitialize() in C#
- If all is wrong, what would be the correct approach?

Thanks in advance
Urs

For direct contact: Remove ALL 4 underscore- characters from e-mail address




Nicholas Paldino [.NET/C# MVP] replied on 05-Apr-07 10:18 AM
Urs,

Yes, it is allowed.  There is nothing stopping you from making the call.

Is it correct?  Absolutely not.

When you create your new thread, you want to call the SetApartmentState
method on the Thread instance before you make any calls to create a COM
component in the thread (preferably, you should call it before you call
Start on the thread).  Given that you need an STA apartment, you want to
pass the STA value from the ApartmentState enumeration.

The reason the component is created correctly on the main thread is
because the entry point of your program has an STAThread attribute on it
which tells the CLR to make that initial thread an STA apartment.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com