在 C# 多线程环境中使用旧版 COM 组件

发布于 2024-08-12 07:39:08 字数 390 浏览 5 评论 0原文

我有遗留的 COM 组件,我的任务是编写包装 COM 并启用并发非阻塞调用的 Web 服务。

首先,因为COM对象本身是无状态的,所以我决定使用[ThreadStatic]属性,这样每个线程都会有自己的COM对象实例,以防止使用lock { }语句并启用真正的并发处理,但它似乎所有调用仍然同步进行。

我编写了一个测试代码,该代码运行与 for { } 循环同步的 COM 组件中的方法,然后添加第二个线程,该线程执行完全相同的操作,但添加到 COM 对象的另一个实例,我没有看到任何变化,X 调用始终消耗 Y时间跨度,与线程数无关。它就像有一个静态锁或其他东西......

尽管如此,单独的进程可以真正同时处理每个调用。什么阻止不同的线程表现相同?

我该怎么做才能实现对 COM 组件的真正并发调用?

I have legacy COM component, and my mission is to write web service that wrap the COM and enable concurrent non-blocking calls.

First of all, because the COM object itself is stateless, i decided to use the [ThreadStatic] attribute so each thread will have its own instance of the COM object to prevent the use of lock { } statement and enable real concurrent processing, but it seems that all calls still procceeded synchronous.

I wrote a test code that runs a method from the COM component synchronous with for { } loop, and then added second thread that doing exactly the same but to another instance of the COM object, and i saw no changes, X calls always consume Y timespan, no matter of threads count. Its like there is a static lock or something...

In spite of that, separate processes can process each one call concurrently for real. What prevent from separate threads to behave the same?

What can i do to enable real concurrent calls to the COM component?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一瞬间的火花 2024-08-19 07:39:08

COM 具有线程感知能力,并将遵循组件类所请求的线程模型。它使用注册表中的 ThreadingModel 值发布其线程要求。如果它设置为“Apartment”(或丢失),COM 将通过返回您 QI 接口的代理来确保所有方法调用都是从单线程单元进行的。代理确保调用被编组到正确的线程。

您可以作弊并使用在 STA 线程中创建组件类时获得的接口指针,并在不进行封送的情况下进行调用。鉴于 coclass 已经表示它不支持多线程,因此它不太可能正常工作。你只会随机破坏内部状态。

COM is threading aware and will honor the threading model requested by the coclass. It publishes its threading requirements with the ThreadingModel value in the registry. If it is set to "Apartment" (or is missing), COM will make sure all method calls are made from a single threaded apartment by returning a proxy for the interfaces you QI. The proxy ensures the call is marshaled to the correct thread.

You could cheat and use the interface pointer that you got when you created the coclass in an STA thread and make calls without marshaling. Given that the coclass already said it isn't capable of multi-threading, this is very unlikely to work correctly. You'll just randomly corrupt internal state.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文