最好的方式来检测导航完成在浏览器控制
本文关键字:浏览器 控制 导航 检测 方式 | 更新日期: 2023-09-27 18:18:41
我有一个带有浏览器控件的表单,并编写了如下代码:
bool DocumentComplete = false;
Form_Activated()
{
for()
{
for()
{
//Some operation
Browser.Navigate(URL);
while(!DocumentComplete)
{
Thread.Sleep(100);
Application.DoEvents();
}
Data = Browser.Document.Body.GetAttribute(some_tag)
//process "Data" and do other stuff
}
}
}
Browser_DocumentComplete()
{
DocumentComplete = true;
}
我有多个for循环和许多变量,这就是为什么我不能粘贴"数据"处理代码在Browser_DocumentComplete()
本身,如:
Browser_DocumentComplete()
{
Data = Browser.Document.Body.GetAttribute(some_tag)
//process "Data" and do other stuff
}
这是正确的方法吗?替代吗?有人建议"定时器"控件或"BackgroundWorker",但我想知道如何修改我的代码来使用定时器而不影响程序的功能。
还有一个问题,如果我使用线程。Sleep暂停代码执行,直到URL完全打开,然后执行此线程。睡眠也暂停了浏览器的导航过程?我的意思是下面的代码是不是更好:
while(!DocumentComplete)
Application.DoEvents();
代替:
while(!DocumentComplete)
{
Thread.Sleep(100);
Application.DoEvents();
}
比起在GUI线程中执行无限循环,你可以在后台线程中启动它,并使用EventWaitHandle类来同步后台线程与WebBrowser。您的代码可以修改如下:
EventWaitHandle DocumentComplete = new EventWaitHandle(false, EventResetMode.AutoReset);
void Form_Activated(object sender, System.EventArgs e)
{
new Thread(new ThreadStart(DoWork)).Start();
}
void Browser_DocumentComplete(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
Data = Browser.Document.Body.GetAttribute(some_tag);
//process "Data" and do other stuff
DocumentComplete.Set();
}
void DoWork() {
for (; ; ) {
for (; ; ) {
//Some operation
Invoke(new NavigateDelegate(Navigate), URL);
DocumentComplete.WaitOne();
}
}
}
void Navigate(string url) {
Browser.Navigate(url);
}
delegate void NavigateDelegate(string url);