我可以等待一个网页浏览器来完成导航,使用for循环? [英] Can I wait for a webbrowser to finish navigating, using a for loop?
问题描述
我有一个循环:
for (i = 0; i <= 21; i++)
{
webB.Navigate(URL);
}
韦伯
是一个WebBrowser控件和 I
是一个int。
webB
is a webBrowser control and i
is an int.
我要等待浏览器来完成导航。
I want to wait for the browser to finish navigating.
我发现<一个href=\"http://stackoverflow.com/questions/583897/c-sharp-how-to-wait-for-a-webpage-to-finish-loading-before-continuing\">this,但是:
- 我不希望使用任何API或加载项
- 我无法用另一个
无效
的功能,如这个答案建议
- I don't want to use any APIs or addins
- I can't use another
void
function, as suggested in this answer
有没有办法等待,而在for循环?
Is there a way to wait while in a for loop?
推荐答案
假设你的主机 web浏览器
在WinFroms应用程序,你可以做到在一个循环方便,高效地,使用异步/的await
模式。试试这个:
Assuming you host WebBrowser
in a WinFroms application, you can do it in a loop easily and efficiently, using async/await
pattern. Try this:
async Task DoNavigationAsync()
{
TaskCompletionSource<bool> tcsNavigation = null;
TaskCompletionSource<bool> tcsDocument = null;
this.WB.Navigated += (s, e) =>
{
if (tcsNavigation.Task.IsCompleted)
return;
tcsNavigation.SetResult(true);
};
this.WB.DocumentCompleted += (s, e) =>
{
if (this.WB.ReadyState != WebBrowserReadyState.Complete)
return;
if (tcsDocument.Task.IsCompleted)
return;
tcsDocument.SetResult(true);
};
for (var i = 0; i <= 21; i++)
{
tcsNavigation = new TaskCompletionSource<bool>();
tcsDocument = new TaskCompletionSource<bool>();
this.WB.Navigate("http://www.example.com?i=" + i.ToString());
await tcsNavigation.Task;
Debug.Print("Navigated: {0}", this.WB.Document.Url);
// navigation completed, but the document may still be loading
await tcsDocument.Task;
Debug.Print("Loaded: {0}", this.WB.DocumentText);
// the document has been fully loaded, you can access DOM here
}
}
现在,是要明白, DoNavigationAsync
异步执行是非常重要的。下面是你从的Form_Load
调用它,处理它的完成:
Now, it's important to understand that DoNavigationAsync
executes asynchronously. Here's how you'd call it from Form_Load
and handle the completion of it:
void Form_Load(object sender, EventArgs e)
{
var task = DoNavigationAsync();
task.ContinueWith((t) =>
{
MessageBox.Show("Navigation done!");
}, TaskScheduler.FromCurrentSynchronizationContext());
}
我已经回答过类似的问题<一href=\"http://stackoverflow.com/questions/18280487/flow-of-webbrowser-navigate-and-invokescript/18283479\">here.
这篇关于我可以等待一个网页浏览器来完成导航,使用for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!