STA(单线程公寓)COM对象 - 产生工作线程? [英] STA (Single Threaded Apartment) COM Object - Spawn worker threads?

查看:135
本文介绍了STA(单线程公寓)COM对象 - 产生工作线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在你的STA COM对象(即COM对象创建一个线程来执行任务)中产生工作线程是一件坏事吗?我想,答案是 - 这取决于!



例如在我的情况:
我使用的工作线程不会干扰/访问COM或COM服务。



我问这是因为STA STA定义STA只能容纳一个线程的原因。产生多线程会违反这个原则,除非工作线程和他们不干扰/处理COM / COM服务的工作。
在这种情况下,我认为这是完全正常的,在我看来工作线程不应该被COM考虑作为逻辑STA的一部分。




解决方案

不,这不是一件坏事。公寓明确存在,以帮助您获得多线程代码工作。一个STA线程是一个不是线程安全的COM服务器的安全的家,COM的公寓线程模型确保它总是以线程安全的方式使用。所有你需要做的是编组接口指针,你想在工作线程中使用(例如IGlobalInterfaceTable),你可以调用方法,而无需做任何特别的。



这不是免费的,当然,有调度的调度涉及的开销。多少取决于STA线程在泵送其消息循环时的响应方式。如果你打算明确地创建工作线程以多线程方式使用COM服务器,那么当然你不会在前面,你让它变慢了。


Is it a bad thing to spawn worker threads in your STA COM object (ie. COM object creates a thread to perform a task)? I think, the answer is - that depends!

For example in my case: The worker threads that I am using will not interfere/access COM or COM Services.

Reason why I am asking this is because by STA COM definition STA can only house one thread. Spawning multiple threads kind of goes against this principle unless the worker threads and the work they do NOT interfere/deal with COM/COM services. In this case I am thinking this is perfectly fine and in my opinion the worker threads should not be considered by COM as part of the logical STA.

What are your thoughts on this?

解决方案

No, that's not a bad thing. Apartments explicitly exist to help you getting multi-threaded code working. An STA thread is a safe home for a COM server that's not thread-safe, COM's apartment threading model ensures that it is always used in a thread-safe way. All you have to do is the marshal the interface pointer you want to use in the worker thread (IGlobalInterfaceTable for example) and you can call the methods without doing anything special.

This doesn't come for free of course, there's overhead involved in marshaling the call. How much depends on how responsive the STA thread is when it pumps its message loop. If you intended to create the worker thread explicitly to use that COM server in a multi-threaded way then of course you'll not be ahead, you made it slower.

这篇关于STA(单线程公寓)COM对象 - 产生工作线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆