multithreadingwinapicomatlapartments

Do apartments "live" on the server side or on the client side in a out-process environment?


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?


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.