我有一个for循环:
for (i = 0; i <= 21; i++) { webB.Navigate(URL); }
webB是一个webBrowser控件,我是一个int.
我想等待浏览器完成导航.
然而,我找到了this:
>我不想使用任何API或插件
>我不能使用另一个void函数,如this answer所示
有没有办法在for循环中等待?
解决方法
假设您在WinFroms应用程序中托管WebBrowser,您可以使用async / await模式轻松高效地循环执行.试试这个:
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调用它并处理它的完成:
void Form_Load(object sender,EventArgs e) { var task = DoNavigationAsync(); task.ContinueWith((t) => { MessageBox.Show("Navigation done!"); },TaskScheduler.FromCurrentSynchronizationContext()); }
我已经回答了类似的问题here.