您的位置:首页 > 其它

COM线程模型 - MTA接口 (传递MTA COM对象给STA套间线程)

2014-08-28 00:13 393 查看
接上篇,能否把一个MTA套间里面创建的COM对象传递个STA套间呢?看MSDN上的说明:

A client or server that supports both single-threaded and multithreaded apartments will have one multithreaded apartment, containing all threads initialized as free-threaded, and one or more single-threaded apartments. Interface pointers must be marshaled
between apartments but can be used without marshaling within an apartment. Calls to objects in a single-threaded apartment will be synchronized by COM. Calls to objects in the multithreaded apartment will not be synchronized by COM.

上面这段文字已经说的很清楚了。我们不可以直接把一个COM对象传递一个另外一个套间。换句话说,只要涉及跨套间,就一定要marshal。

所以前面一篇文章的例子里面,如果辅助线程初始化成STA,那么就不能直接传递COM对象指针了,需要marshal。但是如果辅助线程也是MTA,那么就没有关系了,因为辅助线程和主线程都在MTA里面,同一个套间,无需marshal。

那么如果辅助线程并不属于某个套间,而是一个普通线程呢?

我找到了这些资料:http://support.microsoft.com/kb/150777

NOTE: Current implementations of COM allow a thread that does not explicitly initialize COM to be a part of the MTA. A thread that does not initialize COM is part of the MTA only if it starts using COM after at least one other thread in the process has previously called CoInitializeEx(NULL, COINIT_MULTITHREADED). (It is even possible that COM itself may have initialized the MTA when no client thread has explicitly done so; for example, a thread associated with an STA calls CoGetClassObject/CoCreateInstance[Ex] on a CLSID that is marked "ThreadingModel=Free" and COM implicitly creates an MTA into which the class object is loaded.) See the information on threading model interoperability below.

大概意思如下:

目前的COM设计允许一个没有显式初始化COM的线程成为MTA套间的一部分。只有当另外一个线程已经调用过CoInitializeEx(NULL, COINIT_MULTITHREADED)后,一个没有初始化COM的线程会在开始使用COM属于MTA套间。(有一个可能性是:COM自己会初始化成MTA但是客户并没有显式初始化;比如,一个STA线程在一个标记为"ThreadingModel=Free"的CLSID上调用CoGetClssObject/CoCreateInstance[x],COM会隐式创建一个MTA套间)

ok,针对我们的情况,辅助线程尽管自己没有初始化COM,但是它也是MTA套间里面的一个线程。所以,也不需要marshal。

另外,关于marshal和unmarshal,基本上靠2个函数:

CoMarshalInterThreadInterfaceInStream andCoGetInterfaceAndReleaseStream

前面的文章里面有例子。(在STA跨套间那里)


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: