Another common problem that plasmunications COM developers is within the process within the process of ThreadingModel = Apartment. This specification tells COM, the instance of the object must only be created in STA. It also allows COM freely place these object instances in the STA of any host process.
Suppose the client application has five STA threads, each thread uses CocreateInstance to create an instance of the same object. If the thread is based on STA, and the object is marked as threadingModel = APARTMENT, the five object instances will be created in the object's STA. Because each object instance is running on the thread of its STA, all five object instances can run in parallel.
So far, everything is good. Now consider what happens if these object instances share data. Because objects are executed concurrent threads, two or more objects may attempt to access the same data at the same time. Unless all these accesss are read, it will be disaster. The problem may not appear quickly; they will appear in a closed-related error form, so it is difficult to diagnose and reproduce. This explains the reason why the following is: ThreadingModel = Apartment object should include code synchronously access to shared data unless you can determine that the client's client does not overlap the method of performing access.
The problem is that too many COM developers believe that ThreadingModel = Apartment enables them to freely from code to write threads. The fact is not that - at least not exactly. ThreadingModel = Apartment does not mean that the object must be fully threaded. It represents a commitment to the COM, that is, the data shared by two or more object instances (or the data shared by this object and other objects) It is carried out in a way that thread is safe. The task of providing this thread security should be responsible by you, ie object implementors. Sharing data is a variety of sizes, but most of them appear in the form of static variables declared in a static member variable in the C class in a global variable. Even if this is the harmless statement, the problem is also in the STA:
Static int ncallcount = 0;
NCallCount ;
Because all instances of this object will share a nCallCount instance, write the correct way to write these statements is as follows:
Static int ncallcount = 0;
InterlockInCrement (& nCallCount);
Note: You can use critical regions, interlock functions, or any way you want, but don't forget to access STA-based object-sharing data to synchronize!