打开 Oookii 保存文件对话框时,带有嵌入式 WebView2 的 WPF 应用程序突然关闭,没有任何可见异常

WPF app with embedded WebView2 suddenly shuts down without any visible exception when opening Oookii save file dialog

我正在尝试在我的 WPF 应用程序中使用嵌入式 WebView2 控件,并打开 Ookii VistaSaveFileDialog 以响应来自 webview 的通信。

但是,一旦我 运行 对话框的 ShowDialog 方法(在等待用户响应时阻塞)并且对话框打开,应用程序突然关闭,没有异常或警告.这种情况会间歇性发生。

它似乎只发生在我 运行 调试模式下的代码,使用 VS 调试时。 Release模式好像没有这个问题

删除 binobj 文件夹并重建解决方案没有帮助。

我该如何解决debugging/resolving这个问题?

Target/version 信息: TFM:net6.0-windows
WebView2:1.0.1210.39
Ookii.Dialogs.Wpf: 5.0.1

XAML:

<Window x:Class="_testWebviewDialogs.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wv="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf">
    <wv:WebView2 x:Name="webview" Source="about:blank"/>
</Window>

代码隐藏:

using Ookii.Dialogs.Wpf;
using System.IO;
using System.Windows;

namespace _testWebviewDialogs;
public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();
        initializeAsync();
    }

    private async void initializeAsync() {
        await webview.EnsureCoreWebView2Async();
        var html = await File.ReadAllTextAsync("container.html");
        webview.NavigateToString(html);
        webview.CoreWebView2.WebMessageReceived += (s, e) => {
            var dlg = new VistaSaveFileDialog();
            dlg.ShowDialog(); // Sometimes the app shuts down while in this (blocking) call
            MessageBox.Show(dlg.FileName);
            webview.CoreWebView2.PostWebMessageAsString(dlg.FileName);
        };
    }
}

container.html,复制到输出文件夹:

<!DOCTYPE html>
<html>
<body>
    <button id="button1">Click me</button>
    <script>
        document.getElementById('button1')
            .addEventListener('click', ev => {
                chrome.webview.postMessage('Hello from webview');
            });
    </script>
</body>
</html>

根据我提交的 GitHub 问题上的 suggestion I received,以下内容似乎有效:

webview.CoreWebView2.WebMessageReceived += (s, e) => 
    SynchronizationContext.Current!.Post((_) => {
        var dlg = new VistaSaveFileDialog();
        dlg.ShowDialog();
        MessageBox.Show(dlg.FileName);
        webview.CoreWebView2.PostWebMessageAsString(dlg.FileName);
    }, null);

来源:Threading model for WebView2 apps: Reentrancy