.net 单线程单元 - 无法实例化 ActiveX 控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1418466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:19:17  来源:igfitidea点击:

Single-threaded apartment - cannot instantiate ActiveX control

.netexceptionstasingle-threaded

提问by martin.malek

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.

我需要获取有关 HTML 页面中应用的 CSS 样式的信息。我使用了 AxWebBrowser 并迭代了 IHTMLDOMNode。我能够获得我需要的所有数据并将代码移动到我的应用程序中。问题是这部分在后台工作人员内部运行,并且在尝试实例化控件时出现异常。

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.

Is there any way how to solve this or other option than AxWebBrowser?

除了 AxWebBrowser 之外,有什么方法可以解决这个问题或其他选项吗?

回答by JaredPar

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.

您遇到的问题是大多数后台线程/工作 API 将在多线程单元状态中创建线程。该错误消息表明该控件要求该线程是单线程单元。

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

您可以通过自己创建一个线程并在该线程上指定 STA 单元状态来解决此问题。

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

回答by user764177

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

继续将 [STAThread] 添加到您的应用程序的主条目,这表明 COM 线程模型是单线程单元 (STA)

example:

例子:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

回答by Ahmad

If you used [STAThread]to the main entry of your application and still get the error you may need to make a Thread-Safe callto the control... something like below. In my case with the same problem the following solution worked!

如果您习惯[STAThread]了应用程序的主条目,但仍然收到错误消息,您可能需要对控件进行线程安全调用...如下所示。在我遇到同样问题的情况下,以下解决方案有效!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }