1

我在这里的另一个线程上发现了一个问题,我需要访问一个 STA 的 COM 组件。我将在双核计算机上运行它,使用该组件的进程仅达到50%的CPU。可惜车主说不能把组件改成MTA,因为组件是Matlab编译的混合系统,核心是C。

所以我试图在同一个进程上加载 COM 类的两个实例,不同的线程访问它,但我做不到,只有最后一个 COM 实例可用。你知道什么可以解决这个问题吗?

我正在考虑在同一台计算机上运行我的服务的两个进程,以实现 100% cpu。这不是一个好的解决方案,主要是因为这些服务器将安装在我们的基础设施之外。

4

3 回答 3

2

On the topic of multiple STA components

It is possible to have two instances of the same STA COM component and access them from C#. The only thing that could prevent you from such scenario is the object itself if implemented as a singleton object.

However, if both instances are on the same STA thread, an active call in one of the instances will block any other calls into that thread. Thus, if you want those two instances to work in parallel, you need to have them be on separate STA threads. Just to be on the safe side, I'd create both instances on background threads. That should prevent your UI from locking.

On the topic of STA vs. MTA for the external component

I am not sure why the component being in C would prevent it from being an MTA object. Being MTA just means the object needs to internally synchronize it's state access and management code between multiple threads.

WARNING: Ugly hack! :-) If you want to experiment a bit, you could go to the registry and change the external component threading model from Apartment to Free, just to verify that your code would work properly with an MTA. Their component will probably break, though, as they probably did not write thread-safe code, relying on COM to guard them.

Make a note on a prominent place to revert that change later, so that you don't end up with a system where their code doesn't work and spent countless hours chasing ghosts. :-)

于 2008-11-10T17:00:57.447 回答
0

弗朗西·佩尔诺夫,

我尝试使用两个线程,并在每个线程的上下文中初始化 com 实例,但错误是相同的:(来自 HRESULT 的异常:0x80004005 (E_FAIL))

我正在通过 CallContext GetData 和 SetData 存储和检索实例。

于 2008-11-11T11:16:58.903 回答
-1

Try registering a second class using the same DLL. Consider that you may actually need a separate copy of the DLL with a different name in order to be completely safe.

Just remember that the STA COM class (and perhaps its DLL) is not considered thread safe for multi-threading and there is nothing you can do about that external to the COM class.

于 2008-11-10T16:59:52.143 回答