基于COM开发的经验

摘自: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值