3

I am trying to Initialize Web Browser Component in window form but I am getting this exception message

System.Threading.ThreadStateException: 'ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.'

I am getting above mentioned Exception Message on this line

this.browse = new System.Windows.Forms.WebBrowser();

Please tell me how to solve this issue

3 Answers3

3

Flag your Main() method with [STAThread] like below:

[STAThread]
static void Main()
{
    // your code
}

or, if the Web Browser Component should be called from inside of ant thread you created, set proper Apartment State for this thread:

yourThread.SetApartmentState(ApartmentState.STA);
VillageTech
  • 1,968
  • 8
  • 18
1

Add STAThread attribute above your main method.

ShayK
  • 429
  • 3
  • 6
0

Although too late for OP, I'd like to register here the solution that worked for me.

I got the same error msg in the same position at InitializeComponent();

this.browse = new System.Windows.Forms.WebBrowser();

And same error msg after change control to:

this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();

I tried:

var thread = new Thread(async () =>
{
    using var showDoc = new ShowDoc();
    showDoc.ShowDocTask(_path, OriginalFileName, FileNameExtension);
});
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join(); //Wait for the thread to end

And same error.

Finally, I saw How to force a task to run on an STA thread? [duplicate] that has a Stephen Cleary very interesting answer, and pointed me to the Set ApartmentState on a Task that solved this problem.

The Servy's and David's answers has the code for implement, respectively, a

public static Task<T> StartSTATask<T>(Func<T> func)

and a

public static Task StartSTATask(Action func)

both use new TaskCompletionSource<object>() to carry back to the caller the Result or Exception that results from the Action or Func that is passed to a thread, that as VillageTech has pointed, has to be setted to thread.SetApartmentState(ApartmentState.STA). Only after all pieces in place they do a thread.Start(); and both return a (TaskCompletionSource) tcs.Task i.e., the Result or Exception.

Very complex to think on my on, but after seeing, is as brilliant as is obvious.

PS: I learned a lot in these links; after that, I returned to the MS pages and I finally I understood them a lot too:

How to: Wrap EAP Patterns in a Task and TPL and traditional .NET asynchronous programming,