Wait for WebBrowser DocumentCompleted using AutoResetEvent

纵饮孤独 提交于 2019-12-11 11:25:08

问题


I want my function to wait until the event WebBrowser.DocumentCompleted is completed.

I am using AutoResetEvent and here is my code:

private static WebBrowser _browser = new WebBrowser();
private static AutoResetEvent _ar = new AutoResetEvent(false);

private bool _returnValue = false;

public Actions() //constructor
{
        _browser.DocumentCompleted += PageLoaded;
}

public bool MyFunction()
{
    _browser.Navigate("https://www.somesite.org/");
    _ar.WaitOne(); // wait until receiving the signal, _ar.Set()
    return _returnValue;
}

private void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // do not enter more than once for each page
    if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
        return;

    _returnValue = true;

    _ar.Set(); // send signal, unblock my function
}

Here my problem is, PageLoaded never gets fired, and my function gets stuck on _ar.WaitOne();. How can I fix this issue ? perhaps there is another way to achieve this ?


回答1:


Here is how you can synchronously get the page data of a website. This will help me build my web automation API. Special thanks to @Noseratio he helped me finding this perfect answer.

private static string _pageData = "";

public static void MyFunction(string url)
{
    var th = new Thread(() =>
    {
        var br = new WebBrowser();
        br.DocumentCompleted += PageLoaded;
        br.Navigate(url);
        Application.Run();
    });
    th.SetApartmentState(ApartmentState.STA);
    th.Start();
    while (th.IsAlive)
    {
    }

    MessageBox.Show(_pageData);
}

static void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var br = sender as WebBrowser;
    if (br.Url == e.Url)
    {
         _pageData = br.DocumentText;
        Application.ExitThread();   // Stops the thread
     }
    }
}


来源:https://stackoverflow.com/questions/35400849/wait-for-webbrowser-documentcompleted-using-autoresetevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!