我有一个 for 循环:
for (i = 0; i <= 21; i++)
{
webB.Navigate(URL);
}
webB
是一个 webBrowser 控件,i
是一个 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 .
关于c# - 我可以使用 for 循环等待网络浏览器完成导航吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303758/