C# 在webbrowser控件中检测导航完成的最佳方法
我有一个带有webbrowser控件的表单,并编写了如下代码:C# 在webbrowser控件中检测导航完成的最佳方法,c#,winforms,browser,webbrowser-control,webclient,C#,Winforms,Browser,Webbrowser Control,Webclient,我有一个带有webbrowser控件的表单,并编写了如下代码: bool DocumentComplete = false; Form_Activated() { for() { for() { //Some operation Browser.Navigate(URL); while(!DocumentComplete) { Thread.Sleep(100); Application.
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循环和许多变量,这就是为什么我无法将“数据”处理代码粘贴到浏览器\u DocumentComplete()
Browser_DocumentComplete()
{
Data = Browser.Document.Body.GetAttribute(some_tag)
//process "Data" and do other stuff
}
这是正确的方法吗?还有别的选择吗?有人建议使用“Timer”控件或“BackgroundWorker”,但我想知道如何修改代码以使用Timer而不影响程序的功能
还有一个问题,如果我使用Thread.Sleep暂停代码执行直到URL完全打开,那么这个Thread.Sleep是否也会暂停webbrowser的导航过程?我的意思是,以下代码是否更好:
while(!DocumentComplete)
Application.DoEvents();
而不是:
while(!DocumentComplete)
{
Thread.Sleep(100);
Application.DoEvents();
}
您可以在后台线程中启动无限循环,并使用该类将后台线程与WebBrowser同步,而不是在GUI线程中执行无限循环。您的代码可能会发生如下更改:
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);