在UnhandledException上显示消息对话框

时间:2018-04-09 08:27:28

标签: 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();
}

1 个答案:

答案 0 :(得分:3)

这是可能的,但您需要确保在显示UnhandledExceptionEventArgs.Handled之前将MessageDialog属性设置为true。如果未设置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();
}

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