System.Threading.ThreadStateException while instantiating WebBrowser control

D

Duncan Bayne

Hi All,

I have an WinForms 2.0 application that creates a user control, which
contains a System.Windows.Forms.WebBrowser control.

This works fine until I refactor the application to only create the user
control upon an event being fired. Then, this line in the
designer-generated InitializeComponent() method throws a
System.Threading.ThreadStateException exception:

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

This problem is explained in the following KB article:

http://support.microsoft.com/default.aspx?scid=kb;en-us;841295

However, none of the three solutions proposed actually help me. The Main
method already has the STAThread attribute, and the thread in which the
control is being created isn't actually created by my code, it's created
when the event fires.

So, does anyone have any advice to share on this? How *do* I ensure that
the thread that creates the web browser control via. the event is in a
single-threaded apartment? I suspect I'm missing something here that would
be obvious to someone with more COM experience than I have.

As an aside: wasn't WinForms supposed to make this kind of thing easier? :p

Yours,
Duncan Bayne
 
S

Stoitcho Goutsev \(100\)

Duncan,

I'm not an COM expert, but even if you set the STA for the executing thread
you can host this control in the for because the form is created in a
different thread.

What I'd suggest is to marshal the event call to the main UI thread using
Control.Invoke and then create the web control there.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top