Thursday, November 27, 2008

Server Side


The ATL Wizard makes COM server creation extremely easy. The first step in creating a COM coclass is coming up with one or more pieces of functionality that you want to separate from the main body of an application's code. You probably want to separate the functionality in order to make it reusable across multiple applications. But you may also want to do it because it allows a team of programmers to divide easily into

separate working groups, or because it makes code development or maintenance easier. Whatever the reason, defining the functionality is the first step. One thing that makes defining the boundary easy is the fact that a COM server can act almost identically to a normal C++ class. Like a class, you instantiate an instance of the COM class and then start calling its methods. The syntax of COM instantiation and method calling is slightly different from the syntax in C++, but the ideas are identical. If a COM server has only one interface, then it is, for all practical purposes, a class. (You still have to obey the rules of COM when accessing the object.)

Once you have decided on the functionality and the methods that will be used to access it, you are ready to build your server. As we saw in Understanding DCOM - Part I, there are four basic steps to creating a server:

1. Use the ATL Wizard to create the shell for your COM server. You choose whether you want the server to be a DLL, an EXE or a service.

2. Create a new COM object inside the server shell. You will choose the threading model. This creates the interface into which you can install your methods.

3. Add the methods to your object and declare their parameters.

4. Write the code for your methods.Each of these tasks has been described in detail in the previous article entitled Understanding a Simple COM Server.


After the first installment of "Understanding DCOM" appeared, one frequently asked question concerned threading models. Specifically, what is the difference between apartment-threaded and free-threaded COM objects? The easiest way to understand the difference is to think of apartment-threaded COM objects as single-threaded, while thinking of free-threaded COM objects as multi-threaded.

In apartment threading, method calls from multiple clients are serialized in the COM object on the server.


That is, each individual method call completes its execution before the next method call can begin. Apartment-threaded COM objects are therefore inherently thread safe. Freethreaded

COM objects can have multiple method calls executing in the COM object at the same time. Each method call from each client runs ona different thread. In a free-threaded COM object you therefore have to pay attention to multi-threading issues such as synchronization.

Initially you will want to use apartment threading because it makes your life easier, but over time the move to free threading may offer you

more advantages.

0 comments: