首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我可以等待浏览器完成导航,使用for循环吗?

我可以等待浏览器完成导航,使用for循环吗?
EN

Stack Overflow用户
提问于 2013-08-18 21:16:30
回答 7查看 14.5K关注 0票数 7

我有一个for循环:

代码语言:javascript
运行
复制
for (i = 0; i <= 21; i++)
{
  webB.Navigate(URL);
}

webB是一个webBrowser控件,i是一个int。

我想等待浏览器完成导航。

然而,我找到了

  • 我不想使用任何API或加载项
  • 我不能像在void中建议的那样使用另一个这个答案函数

在for循环中有等待的方法吗?

EN

Stack Overflow用户

回答已采纳

发布于 2013-08-19 02:43:36

假设您在一个WebBrowser应用程序中承载了WinFroms,那么您可以使用async/await模式在一个循环中轻松高效地完成这个任务。试试这个:

代码语言:javascript
运行
复制
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调用它并处理它的完成:

代码语言:javascript
运行
复制
void Form_Load(object sender, EventArgs e)
{
    var task = DoNavigationAsync();
    task.ContinueWith((t) =>
    {
        MessageBox.Show("Navigation done!");
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

我回答了一个类似的问题,这里

票数 7
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18303758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档