开发者

STAThead on a DLL for using with Task/BackgroundWorker

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? O开发者_如何学Cf 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.SetApartmentState before starting it. You'll then need to use Control.BeginInvoke to marshal calls back to the UI thread - you don't want to use BackgroundWorker or Task, 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 WebBrowserControl you'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜