CoInitialize in C# ?



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
.



Relevant Pages

  • Re: CoInitialize in C# ?
    ... which tells the CLR to make that initial thread an STA apartment. ... and once in a secondary thread. ... in the worker thread function, before instantiating the 2nd COM object. ... Isn't there a pendant for CoInitialize() in C# ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: start a new thread for a COM object
    ... That's surely the way to go -- use AfxBeginThread to create the new thread - ... in the thread make sure you call CoInitialize at the begining and ... then instantiate your COM object. ...
    (microsoft.public.vc.language)
  • Re: MFC and number of times COM intialized
    ... "CoInitialize could be called more than once in an application. ... first successful call will return NOERROR; ... I have a working MFC based application which intializes COM only once ... secondary thread. ...
    (microsoft.public.vc.mfc)
  • Re: CoInitialize versus CoInitializeEx
    ... instantiate the third party object in the main thread and then use one or ... single-threaded apartment. ... need to be marshaled to the worker thread before the worker thread can use ... It's not immediately clear to me why the third party COM object is failing ...
    (microsoft.public.win32.programmer.ole)
  • Re: Callback from a thread
    ... Mike Ober. ... monitoring class will be running in the secondary thread so it should ... I have a worker thread that needs to ...
    (microsoft.public.dotnet.languages.vb)