加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我可以等待webbrowser使用for循环完成导航吗?

发布时间:2020-12-15 04:29:29 所属栏目:百科 来源:网络整理
导读:我有一个for循环: for (i = 0; i = 21; i++){ webB.Navigate(URL);} webB是一个webBrowser控件,我是一个int. 我想等待浏览器完成导航. 然而,我找到了this: 我不想使用任何API或插件 我不能使用另一个void函数,如this answer所示 有没有办法在for循环中等待
我有一个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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读