Winforms: One COM object needs an STAThread, the other needs an MTAThread. How can I use them?

让人想犯罪 __ 提交于 2019-12-22 17:39:40

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/1521816/winforms-one-com-object-needs-an-stathread-the-other-needs-an-mtathread-how-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!