Can not create an ActiveX control instance because the current thread is not in an STA

3

I'm trying to access a website through the WebBrowser and this morning suddenly the following error appeared

  

You can not create an instance of the ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' because the current thread is not in a STA (single-threaded apartment).

I can not solve it, because I had never been in contact with this type of error.

Following is part of the code:

string sSite = "http://online.sefaz.am.gov.br/diselada/consultadi.asp";
Uri sUri = new Uri(sSite);

WebBrowser webSiscomex = new WebBrowser();
webSiscomex.AllowNavigation = true;
webSiscomex.Navigate(sSite);
webSiscomex.Width = 700;
webSiscomex.Height = 500;
webSiscomex.Visible = true;
webSiscomex.ScrollBarsEnabled = false;
webSiscomex.ScriptErrorsSuppressed = true;
webSiscomex.Show();
    
asked by anonymous 31.07.2017 / 17:00

1 answer

5

Windows applications have two ways to handle threads: Single Thread Apartment and Multithread Apartment . Each model has an approach on how objects can be accessed.

The differences between both models are a very extensive study. For an hour, you need to know that visual controls for Windows applications can only work on the Single Thread Apartment (STA) model, whereas controls that handle threads (ie: background worker) typically create threads in the model Multithread apartment (MA) .

I think you instantiate the WebBrowser on a separate thread from the main thread of the form, right? The solution is to force the thread where you instantiate the WebBrowser to use the STA template, like this:

Thread t = new Thread(foo); // onde foo é o método que a Thread t irá executar
t.SetApartmentState(ApartmentState.STA);
t.Start();

I based the above on in this answer on the English OS .

    
31.07.2017 / 17:26