Winforms:一个COM对象需要一个STAThread,另一个需要MTAThread。我该如何使用它们?

编程入门 行业动态 更新时间:2024-10-27 00:28:50
本文介绍了Winforms:一个COM对象需要一个STAThread,另一个需要MTAThread。我该如何使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试用两个COM组件构建Winforms应用程序。但是,一个组件仅在使用 [MTAThread] 时有效,而另一个组件仅在 [STAThread] 时有效。 / p>

推荐的解决方案是什么?

解决方案

Windows窗体需要[ STAThread]出现在它的主要入口点上。它仅在单线程单元状态下工作。您可以在Windows窗体的UI线程上使用STA COM对象,而不会出现任何问题。

典型的方法是创建自己的线程,并设置 Thread.ApartmentState (尽管这是默认值)。

ThreadStart threadEntryPoint = ...;初始化并使用您的MTA线程COM组件。 var thread = new Thread(threadEntryPoint); thread.ApartmentState = ApartmentState.MTA; //在调用Start()之前进行设置! thread.Start();

I'm trying to build a Winforms application with two COM components. However, one of the components only works when using [MTAThread] and the other only works with [STAThread].

What would the recommended solution be?

解决方案

Windows forms requires [STAThread] to be present on it's main entry point. It will only work in Single threaded apartment state. You can use your STA COM object on the UI thread in Windows Forms, with no issues.

The typical approach for this is to create your own thread, and set the Thread.ApartmentState to MTA (although this is the default) for the separate thread. Initialize and use your MTA-Threaded COM components from within this thread.

ThreadStart threadEntryPoint = ...; var thread = new Thread(threadEntryPoint); thread.ApartmentState = ApartmentState.MTA; // set this before you call Start()! thread.Start();

更多推荐

Winforms:一个COM对象需要一个STAThread,另一个需要MTAThread。我该如何使用它们?

本文发布于:2023-11-25 07:35:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我该   如何使用   对象   Winforms   MTAThread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!