Single-threaded apartment - cannot create ActiveX controls

I need to get information about the applied CSS styles on an HTML page. I used AxWebBrowser and iteration IHTMLDOMNode. I can get all the necessary data and move the code to my application. The problem is that this part works inside the working background, and I got an exception when trying to create an instance of 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 a way to solve this or that option other than AxWebBrowser?

+54
exception sta single-threaded
Sep 13 '09 at 18:21
source share
3 answers

The problem you are facing is that most background threads / work APIs will create a thread in a multi-threaded apartment state. The error message indicates that the control requires that the stream be a single-threaded apartment.

You can get around this by creating a stream yourself and indicating the state of the STA apartment in the stream.

 var t = new Thread(MyThreadStartMethod); t.SetApartmentState(ApartmentState.STA); t.Start(); 
+65
Sep 13 '09 at 18:23
source share

Go ahead and add [STAThread] to the main record of your application, this means that the COM streaming model is a 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()); } } 
+47
May 21 '11 at 17:37
source share

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

 Private void YourFunc(..) { if (this.InvokeRequired) { Invoke(new MethodInvoker(delegate() { // Call your method YourFunc(..); })); } else { /// } 
+3
Dec 12 '14 at 18:16
source share



All Articles