How can I navigate webbrowser synchronously?

I looked around for quite some time, and I noticed that everyone says that the webbrowser works asynchronously, and I think that it is wrong, because when I run Navigate and even implement the documentComplete event, nothing happens.

I noticed that when the main thread (the thread that owns the web browser) completed its work only then, the web browser will start navigation, perhaps because after that the browser will use the main thread to execute its commands.

Now this is not good, because I want to be able to control the time, I want to know when the web browser loaded the page, and then continue to work. The survey does not work here because of what I said earlier, the web browser does not even start navigation.

Example:

WebBrowser browser = new WebBrowser(); browser.Navigate(url); while(browser.ReadyState != WebBrowserReadyState.Complete) { } // Then executing the next steps... 

How can I use WebBrowser synchronously so that I can use the document property and other WebBrowser elements, I want to create some kind of locking method. That way, I can control and know when WebBrowser completed the download.

+4
source share
1 answer

When you move your main thread, you will not wait for the document to complete. Therefore, you need to block it with the global varibale. A dirty solution can be:

  bool IsReady; void Go() { IsReady = false; brw.Navigate("url"); do { Thread.Sleep(10); Application.DoEvents(); } while (!IsReady); } void brw_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { IsReady = true; } 

But the trick here is when an exception occurs, it will silently stop your code without any explicit exception. Therefore, I highly recommend using the code associated with the webbrowser inside the catch try block.

+6
source

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


All Articles