Single-threaded apartment - cannot instantiate ActiveX control

.NetExceptionStaSingle Threaded

.Net Problem Overview


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.

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

.Net Solutions


Solution 1 - .Net

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.

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

Solution 2 - .Net

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (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());
    }
}

Solution 3 - .Net

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

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

Solution 4 - .Net

My problem with this was that I had my Main method marked as async. So fixed it just by making it static void and adding .wait() to all awaitable methods inside.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmartin.malekView Question on Stackoverflow
Solution 1 - .NetJaredParView Answer on Stackoverflow
Solution 2 - .Netuser764177View Answer on Stackoverflow
Solution 3 - .NetAhmadView Answer on Stackoverflow
Solution 4 - .NetGrengasView Answer on Stackoverflow