我有一个带有webbrowser控件的表单,并且编写了如下代码:
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
}
这是正确的方法吗?还有其他选择有人建议使用“Timer”控件或“BackgroundWorker”,但我想知道如何在不影响程序功能的情况下修改代码以使用Timer。
还有一个问题,如果我使用Thread.Sleep暂停代码执行直到URL完全打开,那么这个Thread.Sleep是否还会暂停webbrowser的导航过程?我的意思是以下代码更好:
while(!DocumentComplete)
Application.DoEvents();
而不是:
while(!DocumentComplete)
{
Thread.Sleep(100);
Application.DoEvents();
}
答案 0 :(得分:2)
您可以在后台线程中启动它,而不是在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);