在异步任务中并行使用 WebView2

问题描述

我有一个简单的认 Windows 桌面表单 Form1,带有一个按钮 btn_Go 作为测试。
我想运行多个并行的 WebView2 实例并处理来自呈现页面的 html 代码。 要并行运行 WebView2,我使用 SemaphoreSlim(设置为并行 2)。另一个 SemaphoreSlim 用于等待 WebView2 渲染文档(有一些时间延迟)。

但我的代码落在 await webbrowser.EnsureCoreWebView2Async(); 上。 WebView2 实例 webbrowser 中调试器的内部异常是:

{"Cannot change thread mode after it is set. (Exception from HRESULT: 0x80010106 (RPC_E_CHANGED_MODE))"} System.Exception {System.Runtime.InteropServices.COMException}

如何并行多次调用 WebView2 并处理所有 url?

完整的演示代码

using Microsoft.Web.WebView2.WinForms;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebView2Test
{
  public partial class Form1 : Form
  {
    public Form1() { InitializeComponent(); }

    private void btn_Go_Click(object sender,EventArgs e) { Start(); }

    private async void Start()
    {
        var urls = new List<string>() { "https://www.google.com/search?q=test1","https://www.google.com/search?q=test2","https://www.google.com/search?q=test3" };
        var tasks = new List<Task>();
        var semaphoreSlim = new SemaphoreSlim(2);
        foreach (var url in urls)
        {
            await semaphoreSlim.WaitAsync();
            tasks.Add(
            Task.Run(async () => {
                try { await Startbrowser(url); }
                finally { semaphoreSlim.Release(); }
            }));
        }
        await Task.WhenAll(tasks);
    }

    public async Task<bool> Startbrowser(string url)
    {
        SemaphoreSlim semaphore = new System.Threading.SemaphoreSlim(0,1);

        System.Timers.Timer wait = new System.Timers.Timer();
        wait.Interval = 500;
        wait.Elapsed += (s,e) =>
        {
            semaphore.Release();
        };
        WebView2 webbrowser = new WebView2();
        webbrowser.NavigationCompleted += (s,e) =>
        {
            if (wait.Enabled) { wait.Stop(); }
            wait.Start();
        };
        await webbrowser.EnsureCoreWebView2Async();
        webbrowser.CoreWebView2.Navigate(url);

        await semaphore.WaitAsync();
        if (wait.Enabled) { wait.Stop(); }

        var html = await webbrowser.CoreWebView2.ExecuteScriptAsync("document.documentElement.outerHTML");
        return html.Length > 10;
    }
  }
}

我已经安装了 WebView2 runtime

-- 测试

在主线程中准备WebView2并将其发送到子线程中。

我已经尝试在主线程 WebView2Start 方法中创建 var bro = new List<WebView2>() { new WebView2(),new WebView2(),new WebView2() }; 列表并将 WebView2 实例发送到 await Startbrowser(bro[index],url); ......但这以相同的方式结束错误

解决方法

您可以尝试使用以下自定义 Task.Run 方法替换代码中的 TaskRunSTA

public static Task TaskRunSTA(Func<Task> action)
{
    var tcs = new TaskCompletionSource<object>(
        TaskCreationOptions.RunContinuationsAsynchronously);
    var thread = new Thread(() =>
    {
        Application.Idle += Application_Idle;
        Application.Run();
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return tcs.Task;

    async void Application_Idle(object sender,EventArgs e)
    {
        Application.Idle -= Application_Idle;
        try
        {
            await action();
            tcs.SetResult(null);
        }
        catch (Exception ex) { tcs.SetException(ex); }
        Application.ExitThread();
    }
}

此方法启动一个新的 STA 线程,并在该线程内运行一个专用的应用程序消息循环。您作为参数传递的异步委托将在此消息循环上运行,并安装适当的同步上下文。只要您的异步委托不包含任何配置为 await.ConfigureAwait(false),您的所有代码,包括由 WebView2 组件引发的事件,都应该在该线程上运行。


注意: TBH 我不知道处理 Application.Idle 事件的第一次出现是否是在消息循环中嵌入自定义代码的最佳方式,但它似乎很有效好。值得注意的是,这个事件是从一个内部类ThreadContextsource code)附加和分离的,并且这个类每个线程都有一个专用的实例。因此,每个线程都会接收与在该线程上运行的消息循环相关联的 Idle 事件。换句话说,不存在接收源自其他不相关消息循环的事件的风险,该事件在另一个线程上并发运行。