Ati*_*ris 5 c# parallel-processing multithreading semaphore 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我安装了WebView2 运行时。
--测试
WebView2
在主线程中准备并将其发送到子线程中。
我已经尝试从主线程创建方法WebView2
列表并将 WebView2 实例发送到...但这以相同的错误结束。Start
var bro = new List<WebView2>() { new WebView2(), new WebView2(), new 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();
}
}
Run Code Online (Sandbox Code Playgroud)
此方法启动一个新的 STA 线程,并在该线程内运行专用的应用程序消息循环。作为参数传递的异步委托将在此消息循环上运行,并安装适当的同步上下文。只要您的异步委托不包含任何await
配置.ConfigureAwait(false)
,您的所有代码(包括组件引发的事件WebView2
)都应该在此线程上运行。
注意:说实话,我不知道处理Application.Idle
事件的第一次出现是否是在消息循环中嵌入自定义代码的最佳方法,但它似乎工作得很好。值得注意的是,这个事件是与一个内部类ThreadContext
(源代码)附加和分离的,并且这个类每个线程都有一个专用的实例。因此,每个线程都会接收Idle
与该线程上运行的消息循环关联的事件。换句话说,不存在接收源自某个其他不相关消息循环(在另一个线程上并发运行)的事件的风险。
归档时间: |
|
查看次数: |
3930 次 |
最近记录: |