So as the title suggests, I'm trying to use WebBrowser control in a class library. I've gone through several SO questions like this excellent post, but the unique thing in my situation is that the WebBrowser object must remain alive for the life of application and keep its state/cookies across different calls that the library clients will make from time to time.
I have confirmed that WebBrowser control does not do navigation unless the thread it was created on contains a message pump. But as soon as I introduce a message pump, the code blocks at Application.Run()
call and no further events are generated. Any help will really be appricated.
If I understood the question correctly, you need to run an instance of
WebBrowser
control for the lifetime of your library, and keep it alive and independent on a dedicated STA thread with its own WinForms message loop.The code below shows how it can possibly be done, using a helper class called
MessageLoopApartment
. Note how theWebBrowser
gets created and manipulated on a separate thread.The Task Parallel Library is very handy in getting the synchronization job done. The tasks scheduled on the STA thread with
MessageLoopApartment.Run
can be waited synchronously withtask.Wait()
or asynchronously withawait task
, results and exceptions are propagated from the STA thread viaTask.Result
/Task.Execption
, exceptions are re-thrown on the caller's stack frame.The implementation of
MessageLoopApartment
is compatible with NET 4.0, it doesn't use any .NET 4.5 features. The client code (theWebBrowser
navigation test) optionally usesasync/await
, which may requireMicrosoft.Bcl.Async
to target .NET 4.0. TPL andasync/await
greatly simplify manipulating objects created inside theMessageLoopApartment
's thread, like_webBrowser
.The navigation test is performed inside
MainForm_Load
, but the lifetime of_webBrowser
and_apartment
is not limited by the boundaries of that single call. Both gets destroyed insideMainForm_FormClosed
. The test app is a WinForms app, but it may as well be a console app or anything else.