用于驱动 STA 模型 .NET 库组件的 TimerCallback 委托
我正在尝试使用 TimerCallback Delegate 机制来驱动来自第 3 方 .NET 库组件的对象实例,该实例位于按定时执行的单独线程上。
当我尝试从库中创建对象的实例时,出现异常:
(对象名称)只能从以下位置调用 单线程单元 (STA)
作为我的应用程序入口点的子主程序被标记为 MTAThread,如 msdn 上的 Microsoft 示例 此处
I'm trying to use the TimerCallback Delegate mechanism to drive instances of objects from a 3rd party .NET library component on separate threads executing on a timed basis.
When I try to create an instance of an object from the library I an exception is raised:
(object name) can only be called from
a single-threaded apartment (STA)
The sub main which is the entry point for my application is marked MTAThread as in the Microsoft example on msdn here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
单线程 COM 组件有一个硬性要求,即您必须在 STA 线程上创建它们。您可以通过使用 Main() 方法上的 [STAThread] 属性和通过泵送消息循环来创建它。比如通过Application.Run()创建的。
您现在可以从工作线程或计时器回调调用此类组件。 COM 确保满足组件的单线程要求并封送对 STA 线程的调用。对组件的所有调用仅在一个线程上运行,这违背了您想要完成的任务。你会让它变慢,而不是更快。编组调用的速度不快。
这里没有秘密武器,您不能神奇地将明确声明不支持线程的组件转变为线程组件。这也很常见,绝大多数 COM 组件或 .NET 组件都不支持线程。 COM 和 .NET 组件之间的区别在于 COM 对此做了一些事情。 .NET 组件通常只会在某种线程竞争中出现故障,而无需进行诊断。
Single-threaded COM components have a hard requirement that you create them on an STA thread. Which you create by using the [STAThread] attribute on your Main() method and by pumping a message loop. Such as the one created by Application.Run().
You can now call such a component from a worker thread or a timer callback. COM ensures that the single-threaded requirement for the component is met and marshals that call to the STA thread. Defeating what you were trying to accomplish, all calls to the component run on only one thread. You'll make it slower, not faster. Marshaling the call is not fast.
There is no secret sauce here, you cannot magically turn a component that explicitly stated that it doesn't support threading into a threaded component. Nor is it uncommon, the vast majority of COM components, or for that matter .NET components, do not support threading. The difference between COM and .NET components is that COM does something about it. A .NET component will typically just malfunction on some kind of threading race without a diagnostic.