Create a web browser control on a background thread in background work

Is it possible to create a WebBrowser control on a background thread in the BackgroundWorker?

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Using web1 As New WebBrowser

    End Using
End Sub

      

This throws the following error:

The ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' The current thread cannot be located in a single threaded apartment.

Does anyone know a way to create a background WebBrowser? I would like to do this to extract information from websites, then spit out various HTML DOM arrays

+2


source to share


4 answers


Set the apartment state of your stream before the stream starts:



myThread.IsBackground = false;
myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();

      

+1


source


The thread that launches Webbrowser must be ApartmentState .STA. From the BackgroundWorker thread, you will have to use Invoke on the UI object and add a Webbrowser to that context.



I don't think you really need to run the WebBrowser object on a background thread. All of its functions are processed asynchronously with events.

0


source


You can also write a wrapper class that creates web browser controls, creates methods that wrap your retrieval functions, and fire the results through public events.

Here, you simply create a new instance of your wrapper and add it to the ThreadPool.

Don't forget to make the correct call to the owner thread to avoid cross-thread exceptions;)

0


source


After getting down both roads, I would recommend WatiN , an open source library for IE and Firefox automation. The WebBrowser control is good for displaying content, but for anything more complex it becomes a big problem.

0


source







All Articles