c# - 我可以使用 for 循环等待网络浏览器完成导航吗?

标签 c# webbrowser-control

我有一个 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/

相关文章:

c# - Azure AD B2C 和图 : cannot list users with memberOf

c# - 在 WPF TreeView 中获取 FullPath?

同一站点上多用户登录的 C# 应用程序

c# - 如何在 webbrowser 控件中获取链接样式表的地址

c# - 使用 Webbrowser 控件获取和发布数据?

c# - 防止显示 Windows 安全窗口

c# - 找不到类型或命名空间 "SafeIntDictionary"

c# - 将无序列表中的数据与 C# 中的 POCO 一起或与 POCO 一起发回 Controller 操作

C#/.Net 使用 ThreadLocal 和 Async/Await

excel - 如何在 Excel VBA 表单中嵌入浏览器?