Unable to create an instance of Activex control because the current thread is not in an STA

Asked

Viewed 1,156 times

3

I’m trying to access a website through Webbrowser and this morning, suddenly, the following error appeared

Unable to create an Activex control instance '8856f961-340a-11d0-a96b-00c04fd705a2' because the current thread is not in an STA (single-threaded Apartment).

I am not able to solve, because I had never been in contact with this type of error.

Follow a 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();
  • Does this question help you?

  • Can you explain better? I don’t understand, your question!

  • Wow, I’m sorry rs... I forgot to put the link! Take a look at this link and see if it helps you! https://stackoverflow.com/questions/1418466/single-threaded-apartment-cannot-instantiate-activex-control

  • Ah! Ta comes! Thank you!

1 answer

5


Windows applications have two ways to deal with 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 now you need to know that the visual controls of Windows applications in general can only work on the model Single Thread Apartment (STA), while threaded controls (i.e.: background worker) generally create threads in the model Multithread Apartment (MA).

I think you instantiate the Webbrowser in a thread separate from the main thread of the form, right? The solution is to force the thread where you instantiate the Webbrowser to use the STA model, thus:

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 supposed above in the OS in English.

  • 2

    I understood and made this implementation here. And it worked great! I didn’t know it. Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.