在 UnhandledException 上显示消息对话框 [英] Displaying message dialog on UnhandledException

查看:18
本文介绍了在 UnhandledException 上显示消息对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my App I want to display a message dialog whenever there is any Unhandled exception. But it seems that dialog message is not appearing when Unhandled exception is throw, Is it valid to display message popup? Also in MSDN documentation I didn't find much info for it.

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

Below is the test code which I am using:

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

推荐答案

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

It is possible, but you need to make sure to set the UnhandledExceptionEventArgs.Handled property to true before you display the MessageDialog. If the Handled property is not set, the OS will terminate the app immediately after the event handler returns, which in this case is as soon as the execution gets to the await dialog.ShowAsync(). Because the app is immediately terminated, you don't even get the chance to see the dialog.

理想的实现应该是这样的:

The ideal implementation would look like this:

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

Once the user confirms the MessageDialog, the app is programmatically terminated. It is a good course of action because after the unhandled exception we likely don't know what state the app is in and probably can't recover. You could also perform some sort of logging or offer the user to send an error report.

这篇关于在 UnhandledException 上显示消息对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆