Eight lessons of COM experience (1): Always call Coinitialize (EX)

xiaoxiao2021-03-06  14

A few months ago, I received a friend's email, he worked in a famous hardware company. His company has written a very complex COM-based application that uses many processes and local (processes) COM components. At the beginning, the application creates a COM object to serve various client threads running in multi-threaded units (MTAs). This object can also hosted to MTA, which means that the interface pointer can be freely exchanged between the client thread. In the test, my friend found that everything is good before the application is ready to close. Then, I don't know why, the call to Release (you must do this, to correctly release the client-side interface pointer) is locked. His question is: "Where is the problem?"

In fact, the answer is very simple. The application's developers are all right, only one exception, and this is very important: they do not call Coinitialize or CoinitializeEx in all client threads. One of the basic principles of modern COM is that each thread using COM should call Coinitialize or CoinitializeEx first to initialize COM. This principle is unable to avoid. In addition to other things, Coinitialize (EX) should put the thread into the unit and initialize the important per-thread status information (which is required for COM's correct operation). Calling Coinitialize (EX) Failed usually exhibits early COM API functions early in the application life period, the most common is to activate the request. But sometimes the problem is very hidden until everything is too late (for example, it is not returned to Release calls). When the development team adds Coinitialize (EX) to all threads that come into contact with COM, their problems are solved.

Ironically, Microsoft is actually one of the COM programmers sometimes not calling Coinitialize (EX). Some documents contained in the Microsoft Knowledge Base that call Coinitialize (EX) is not required for MTA-based threads (for example, see Articles Q150777). Yes, in many cases, we can skip Coinitialize (EX) without problems. However, this should not, unless you know what you are doing, and you can absolutely do you will not be negatively affected. Calling Coinitialize (ex) is no harmful, so I suggest COM programmers always call it from a COM-related thread.

转载请注明原文地址:https://www.9cbs.com/read-48092.html

New Post(0)