Question

I' having an hard time trying to understand COM apartments in outprocess environment.

Basically I can't understand why the client is required to call CoInitializeEx to register it's own thread in an apartment. I can understand object used by server threads and server threads living in STA or MTA. But I can't understand why the client should be concerned about this.

Every documentation/guide says the client has to call CoInitializeEx to register itself in an apartment. Does that mean that the server keeps tracks of client's threads? Or that the apartment data is allocated on the client process as well?

Was it helpful?

Solution

COM objects that reside in an out-of-proc server actually consist of two parts - an implementation code in the server and an RPC proxy/stub code created by the compiler and the COM runtime. Calling a remote COM object translates to a call to a local proxy object that then uses some RPC mechanism to marshal and transmit the call as a message to the server process. The message is picked by the stub in the server that then calls the real COM object and marshals the result back to the proxy that then unmarshals it and returns it to the calling client code. From the point of view of both the client and the COM object all calls are local, even if the occur over the network as is the case with DCOM.

Now the proxy in the client behaves like a normal COM object and it has to reside in some sort of apartment. The COM object in the server also resides in its own apartment. COM allows for the client and the server to have different threading models and handles the proper synchorinsation (which is dead easy when the two interoperating pieces of code reside in different processes).

I would suggest that you read the Process, Thread, and Apartments part of the COM guide on MSDN to get a better idea which one is what and how they are interconnected.

OTHER TIPS

It is not server to track threads, it is COM attaching thread to certain apartment. And it is client to own threads, so it is client's choice to create STA or MTA.

Once client chose desired apartment model for the thread, COM will decide how exactly satisfy certain calls. If a COM class is registered to run in MTA only, and client's threda is STA, then it is job for COM to take care of creating actual object on worker MTA thread and to marshal its interface into client's STA.

Client chooses mode of operation, COM gets it all together with server's registration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top