Good morning,
I made a simple dll in which I use a WebBrowser control to do some simple tasks. Now I want to use its methods from the main UI in a separate Task or a BackgroundWorker. The problem is that whenever I use the methods I get the “no STAThread” exception… How can I get around this? Of course, in the dll there is no Main() method and I can’t either add the STAThread attribute to the constructor.
Thank you very much.
Well, to get code running in a new STA thread you should create a new thread and explicitly force it to be an STAThread using
Thread.SetApartmentStatebefore starting it. You’ll then need to useControl.BeginInvoketo marshal calls back to the UI thread – you don’t want to useBackgroundWorkerorTask, as those will use a threadpool thread.On the other hand, it’s not clear whether that will help in this case – if you’re using a
WebBrowserControlyou’ll probably need a message loop running etc.It’s not really clear what you mean by “use its methods from the main UI”. Is this WebBrowserControl part of the UI which is running in the normal UI thread? If so, you’ll need to marshal to that thread from the other thread (e.g. using
Control.BeginInvoke) – and the other thread doesn’t need to be an STA thread for that to happen.