使用AutoResetEvent等待WebBrowser DocumentCompleted [英] Wait for WebBrowser DocumentCompleted using AutoResetEvent

查看:188
本文介绍了使用AutoResetEvent等待WebBrowser DocumentCompleted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的功能等待直到事件 WebBrowser.DocumentCompleted 完成。

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

我正在使用 AutoResetEvent ,这里是我的代码:

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
}

这里我的问题是,PageLoaded永远不会我的功能被卡在 _ar.WaitOne(); 上。如何解决这个问题?也许还有另一种方法来实现这一点?

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 ?

推荐答案

这是您如何同步获取网站的页面数据。这将帮助我构建我的Web自动化API。特别感谢@Noseratio他帮助我找到了这个完美的答案。

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
     }
    }
}

这篇关于使用AutoResetEvent等待WebBrowser DocumentCompleted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆