How to WebBrowser.Navigate () from BackgroundWorker?

The only reason I decided to use BackgroundWorker for the application I'm currently developing is to move the long-running multi-user view through the WebBrowser away from the user interface stream.

But doesn't WebBrowser.Navigate() access the user interface?

In other words, I went through all these efforts just to land in the same place (or, even worse, because I have no idea what side effects a non-UI stream may have when accessing user interface controls) .

I am sure that I am not the first who wants to implement something like this, so my question is: what is an acceptable way to solve this problem? those. to WebBrowser.Navigate() from BackgroundWorker ?

+4
source share
1 answer

Navigate() not a blocking call (see the first line in the MSDN docs ), but it updates the interface, and therefore it must be called from the user interface thread.

You have several options:

  • Marshal Navigate() calls UI thread from BackgroundWorker via Invoke call
  • Do not use BackgroundWorker - just make a call to Navigate() from your user interface (for example, a button click event handler) and listen for the WebBrowser DocumentCompleted event.

Example 1 - see fooobar.com/questions/27308 / ...

Here is a sample code for 2:

 public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void _goButton_Click(object sender, EventArgs e) { _webBrowser.Navigate("http://google.com/"); // Non-blocking call - method will return immediately // and page will load in background } private void _webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { // Navigation complete, we can now process the document string html = _webBrowser.Document.Body.InnerHtml; // If the processing is time-consuming, then you could spin // off a BackgroundWorker here } } 
+3
source

Source: https://habr.com/ru/post/1441899/


All Articles