Pergunta

i have a .NET application which is using a COM component using COM Interop, The Component instanciate itself and interface pointer is returned in an API cal to the .net wrapper, at a later point in the application flow a call is made to the COM component.

//Pseudo code 

//CLISD_ITEM is a another CoClass housed by this COM component, the component is a STA based dll 

HRESULT GetItem(ITem **ptr)

{

HRESULT hr = CoCreateInstance(CLSID_ITEM.....,....(void **) &pItem);

pItem->QI(ptr);

}

my question is should i call CoInitialize and CoUninitialize() inside the function GetItem, as of now i not making these calls and the code seems to be working fine, but there are reports of some intermittent crash when calling CoCreateInstance.

if anyone can help me here.

Foi útil?

Solução

No, CoInitializeEx() must always be called by the owner of the thread. Which is never the component itself, it didn't start the thread. Only the owner can determine which apartment type is correct since it needs to take care of apartment guarantees. In particular, an STA thread must pump a message loop. A component can never provide that guarantee.

And this is done consistently in a .NET app, the CLR always calls CoInitializeEx() before it allows any managed code to run on the thread. The apartment type is selected by the [STAThread] or [MTAThread] on the Main() entrypoint for the startup thread, the Thread.SetApartmentState() call for a worker thread. Threadpool threads always join the MTA.

You'll need to look for another reason for the crash.

Outras dicas

Provided you're using this from a thread marked STA with SetApartmentState within .NET, you shouldn't need to do this.

If you're calling this directly on a UI thread (ie: the main Windows Forms or WPF thread) this will be done for you already.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top