簡體   English   中英

等待使用AutoResetEvent的WebBrowser DocumentCompleted

[英]Wait for WebBrowser DocumentCompleted using AutoResetEvent

我希望函數等待事件WebBrowser.DocumentCompleted完成。

我正在使用AutoResetEvent ,這是我的代碼:

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(); 如何解決此問題? 也許還有另一種方法可以實現這一目標?

這是同步獲取網站頁面數據的方法。 這將幫助我構建Web自動化API。 特別感謝@Noseratio,他幫助我找到了完美的答案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM