简体   繁体   中英

How can I navigate webbrowser synchronously?

I have looked around quite a time and I have noticed that everybody saying that webbrowser is working asynchronously, and I think its wrong, because when I trigger Navigate and even implement the documentComplete event, nothing happens.

I have noticed that when the main thread (the thread that owns the webbrowser) has done his job only then the webbrowser start navigating, probably because after that the browser will use the main thread to execute his commands.

now that not good because I want to be able to control the timing, I want to be able to know when the webbrowser done loading the page and then to continue with my work. Polling doesn't work here because of what I said earlier, the webbrowser doesn't even start navigating.

example:

WebBrowser browser = new WebBrowser();

browser.Navigate(url);
while(browser.ReadyState != WebBrowserReadyState.Complete)
{
}

// Then executing the next steps...

How can I use the WebBrowser synchronously so I can be able to use the document property and other stuff of the WebBrowser, I want to create some sort of a blocking method So I can have control and know when the WebBrowser done loading.

When you navigate your main thread will not wait for document complete. So you need to block it via a 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 happens it will silently stop your code without any explicit exception. So I strongly advice using webbrowser related code inside a try catch block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM