[英]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.