我正在尝试用两个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。我该如何使用它们?
发布评论