COM线程模型的行为

原文:https://msdn.microsoft.com/library/ms809971.aspx

Behavior of the COM Threading Models

COM线程模型的行为

Before any thread can create or manipulate COM objects, it must perform some preliminary initialization to establish its relationship with the COM library. As a result of this process, COM creates an apartment appropriate for the initialization routine: CoInitialize creates a single-threaded apartment (STA), whereas CoInitializeEx with the COINIT_MULTITHREADED flag produces a multi-threaded apartment. The CoInitialize/CoInitializeEx call does not initialize the COM library globally, only the calling thread's use of it, so it's important to remember that this initialization should be done on a per-thread basis. This is typically done early in a thread's work function (ThreadProc).

在任何线程能创建或操作COM对象前,必须执行一些预初始化来创建进程与COM库之间的连接。该操作的结果:COM创建了一个“公寓”适用于初始化例程;CoInitialize用于创建STA,用COINIT_MULTITHREADED标记的CoInitializeEx用于创建MTA。CoInitializeCoInitializeEx调用不能在全局初始化COM库,只有调用的线程能初始化COM对象。因此,应该牢记初始化必须在线程的创建阶段发生。通常应当早于ThreadProc方法。

A single-threaded apartment is associated with the thread that created it, and only that specific thread may execute calls on objects within the apartment. By contrast, a multi-threaded apartment is not associated with any particular thread. It may be called concurrently by any number of threads and objects within it and should subsequently protect their member data.

一个STA与创建该公寓的线程关联,只有特定的线程有可能执行STA创建的COM对象的调用。与此不同,MTA不与任何特定的线程关联。MTA的COM对象的调用可以被多线程并发的处理,并且由线程自己保证数据的安全。

Communication between apartments is done via marshaling, a generic abstraction for passing data across thread or process boundaries. Because calls to single-threaded apartments can only be executed on the thread that created them, other threads that wish to use an object within this apartment marshal the call to the apartment's thread and let the apartment thread execute the call. The apartment thread then marshals the return value back to the calling thread.

公寓见的通信通过封送形式,封送是一个通用的抽象用于传递数据穿过线程或进程的边界,由于调用STA创建的COM对象只能被创建该公寓的线程执行,其他线程想要使用在STA创建的(COM)对象可以封送这个调用到创建STA的线程,然后让该线程执行这个调用。STA线程然后封送这个调用返回调用线程。

 

posted on 2018-01-09 20:32  方辰  阅读(114)  评论(0编辑  收藏  举报

导航