Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it important to call CoUninitialize on a thread that will be terminated before my application exits?

I make calls to CoInitializeEx, specifically:

CoInitializeEx(NULL, COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED);

In threads that my application creates, but then terminates before the application exits. Is it important to pair these with CoUninitialize calls, or do those resources get freed when the threads terminate?

like image 555
jeffm Avatar asked Nov 08 '11 17:11

jeffm


1 Answers

Resources are usually returned to the system when the process terminates, not when one of its threads does.

However, CoUninitialize() does not only free resources and unload DLLs, it also enters a modal message loop in order to pump the remaining COM messages before the thread terminates. The documentation says:

If there are open conversations remaining, CoUninitialize starts a modal message loop and dispatches any pending messages from the containers or server for this COM application. By dispatching the messages, CoUninitialize ensures that the application does not quit before receiving all of its pending messages. Non-COM messages are discarded.

Therefore, in order to avoid RPC errors on the callers' side, I'd recommend you follow the documentation's advice and always call CoUninitialize() before terminating threads that have called CoInitializeEx().

like image 160
Frédéric Hamidi Avatar answered Oct 29 '22 03:10

Frédéric Hamidi