基于COM开发的经验

来源:互联网 发布:皇室战争68淘宝 编辑:程序博客网 时间:2024/05/21 09:28

摘自:Eight Lessons from the COM School of Hard Knocks
http://msdn.microsoft.com/library/default.asp?url=/msdnmag/issues/1100/wicked/toc.asp


1.Always Call
CoInitialize(Ex)

    One of the fundamental rules of modern-day COM is that every thread that uses COM should first initialize COM by calling either CoInitialize or CoInitializeEx

2.Don't Pass Raw Interface Pointers Between Threads
   
In preparation for passing the interface pointer to thread B, thread A should marshal the interface pointer like this:
   CoMarshalInterThreadInterfaceInStream (IID_IFoo, pFoo, &pStream);
   Once CoMarshalInterThreadInterfaceInStream has returned, thread B can safely unmarshal the interface pointer:
   IFoo* pFoo;
   CoGetInterfaceAndReleaseStream (pStream, IID_IFoo, (void**) &pFoo);

   you can also transfer interface pointers between threads by placing them in the Global Interface Table (GIT) and having other threads go there to retrieve them. Interface pointers retrieved from the GIT are automatically marshaled when they're retrieved

3.STA Threads Need Message Loops
   (1).STA threads need message loops unless you're confident that they won't be hosting objects that are called from other threads.
    MSG msg;
    while (GetMessage (&msg, 0, 0, 0))
    DispatchMessage (&msg);
    (2).The alternative is to move COM threads to the MTA (or in Windows 2000, the neutral-threaded apartment, or NTA),

4.Apartment Model Objects Must Protect Shared Data
ThreadingModel=Apartment doesn't mean an object has to be completely thread-safe
Error:
    static int nCallCount = 0;
    nCallCount++;
Because all instances of this object will share one instance of nCallCount, the proper way to code these statements is as follows:
Right:
    static int nCallCount = 0;
    InterlockIncrement (&nCallCount);

To wit: use critical sections, interlocked functions, or whatever means you want, but don't forget to synchronize accesses to data shared by STA-based objects!

5.Beware of Launching User

6.DCOM is Firewall-unfriendly

7.Use Threads or Async Calls to Avoid Long DCOM Time-outs

8.Sharing Objects Isn't Easy