问题
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();
}
回答1:
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();
}
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.
来源:https://stackoverflow.com/questions/49728543/displaying-message-dialog-on-unhandledexception