单线程单元 - 无法实例化 ActiveX 控件 [英] Single-threaded apartment - cannot instantiate ActiveX control
问题描述
我需要获取有关在 HTML 页面中应用的 CSS 样式的信息.我使用了 AxWebBrowser 并迭代了 IHTMLDOMNode.我能够获得我需要的所有数据并将代码移动到我的应用程序中.问题是这部分在后台工作程序内部运行,我在尝试实例化控件时遇到异常.
I need to get information about applied CSS styles in HTML page. I used AxWebBrowser and iterate IHTMLDOMNode. I'm able to get all the data I need and move the code into my application. The problem is that this part is running inside of the background worker and I got exception when trying to instantiate the control.
AxWebBrowser browser = new AxWebBrowser();
ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated
because the current thread is not in a single-threaded apartment.
除了 AxWebBrowser 之外,还有什么方法可以解决这个问题或其他选项吗?
Is there any way how to solve this or other option than AxWebBrowser?
推荐答案
您遇到的问题是大多数后台线程/工作者 API 将创建处于多线程单元状态的线程.错误消息表明控件要求线程是单线程单元.
The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.
您可以通过自己创建线程并在线程上指定 STA 单元状态来解决此问题.
You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.
var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();
这篇关于单线程单元 - 无法实例化 ActiveX 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!