January 27th, 2017

How can a COM local server keep itself alive even though there are no active clients?

Suppose you have a COM local server, which means that the COM object is provided by a process different from the clients. And suppose you have a method which triggers some sort of background operation, and the rule for your object is that even if all references to the object are released, the background operation must still run to completion. (This is the model followed by Windows Runtime objects, for example. An asynchronous operation will continue to run independently of the object which initiated the operation.)

The question, then, is how to communicate to the COM infrastructure that you are still doing work and the server should not be shut down just because there are no outstanding references to it.

Assuming the object is MTA-threaded or free-threaded, the recommendation for out-of-process servers is to use Co­Add­Ref­Server­Process and Co­Release­Server­Process to manage their process lifetime. In particular, Co­Release­Server­Process will automatically call Co­Suspend­Class­Objects when the process reference count reaches zero, thereby avoiding the race condition where one thread drops the reference count to zero, and before it can call Co­Suspend­Class­Objects, another thread sneaks in and creates an object.

I’m not the subject matter expert here, so I’ll leave you with some fascinating reading on the subject.

  • This article discusses the issue at hand and covers many of the race conditions that can occur.
  • This article is a more general discussion of free-threaded COM objects.

Warning: Both articles were originally magazine articles, and the tall narrow formatting is carried over to the Web presentation.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.