在 UnhandledException 上显示消息对话框

Dis*_*ant 6 c# uwp

在我的应用程序中,每当出现任何未处理的异常时,我都想显示一个消息对话框。但是在抛出未处理的异常时似乎没有出现对话框消息,显示消息弹出窗口是否有效?同样在 MSDN 文档中,我没有找到太多信息。

以下是我正在使用的测试代码:

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    this.UnhandledException += App_UnhandledException;
}

private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    MessageDialog dialog = new MessageDialog("Unhandled Execption", "Exception");
    await dialog.ShowAsync();
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 7

这是可能的,但您需要确保UnhandledExceptionEventArgs.Handled在显示MessageDialog. 如果Handled未设置该属性,操作系统将在事件处理程序返回后立即终止应用程序,在这种情况下,一旦执行到达await dialog.ShowAsync(). 因为应用程序会立即终止,所以您甚至没有机会看到对话框。

理想的实现如下所示:

private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    e.Handled = true;
    MessageDialog dialog = new MessageDialog("Unhandled Execption", "Exception");
    await dialog.ShowAsync();
    Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)

一旦用户确认MessageDialog,应用程序就会以编程方式终止。这是一个很好的行动方案,因为在发生未处理的异常之后,我们可能不知道应用程序处于什么状态并且可能无法恢复。您还可以执行某种日志记录或让用户发送错误报告。