简体   繁体   English

来自多个线程的COM调用

[英]COM calls from multiple threads

If I call the same COM function from multiple threads to an in proc COM Dll, how thread safe is that? 如果我从多个线程到一个过程COM Dll中调用相同的COM函数,那么线程安全性如何?

Do all my objects in the COM DLL also need to be thread safe for this to work reliably? 我的COM DLL中的所有对象是否也需要是线程安全的才能可靠地工作?

COM takes care of threading on behalf of the COM server. COM代表COM服务器处理线程。 The server publishes the kind of threading it supports with the ThreadingModel registry key. 服务器使用ThreadingModel注册表项发布它支持的线程类型。 Very common settings are Apartment or Both. 非常常见的设置是“公寓”或“两者”。 Free is very rare. 免费是非常罕见的。 A missing key is equivalent to Apartment. 缺少密钥等同于Apartment。

COM requires a single-threaded apartment (STA) for apartment threaded servers. COM需要用于单元线程服务器的单线程单元(STA)。 If you don't provide one (CoInitialize/Ex call) then it will create a dedicated thread for the server. 如果不提供(CoInitialize / Ex调用),它将为服务器创建一个专用线程。 A hard requirement for an STA thread is that it also pumps a Windows message loop. 对STA线程的一个严格要求是它还会产生Windows消息循环。 The message loop is the mechanism by which COM automatically marshals a method call from one thread to another. 消息循环是一种机制,COM通过该机制自动将一个线程之间的方法调用封送给另一个线程。

So, the general answer to your question is, yes, it normally is thread-safe. 因此,对您问题的一般回答是,是的,它通常是线程安全的。 There are still things that can go wrong. 仍有可能出错的地方。 Deadlock is possible when a call is made from a worker thread but the STA thread isn't pumping. 当从工作线程进行调用但STA线程未启动时,可能会发生死锁。 Or the server could be fibbing about the ThreadingModel it registered. 否则服务器可能会对其注册的ThreadingModel轻描淡写。 Not uncommon with servers implemented in .NET. 在.NET中实现的服务器并不少见。 They get registered as Both, but there are few .NET classes that are actually thread-safe. 它们被注册为Both,但是实际上很少有.NET类是线程安全的。

See this very detaled article . 看到这篇非常珍贵的文章 Basically COM will take care of synchronization - you don't need to bother. 基本上,COM将负责同步-您无需费心。 However in certain cases the consumer can experience significant slowdown because of synchronization. 但是,在某些情况下,由于同步,消费者可能会经历明显的减速。

Depends upon the COM objects threading model. 取决于COM对象的线程模型。 If its free threaded then you are responsible for thread safety. 如果它是自由螺纹,则您要负责线程安全。 If its in a single threaded apartment then you can only call it from one, and if it's in a multithreaded apartment, then you can can but as always you have to consider the implications for the object's state. 如果它在单线程单元中,则只能从一个线程中调用它;如果在多线程单元中,则可以,但与往常一样,您必须考虑对象状态的含义。 there is a very good answer on SO Could you explain STA and MTA? SO上有一个很好的答案, 您能解释一下STA和MTA吗? explaining this. 解释这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM