gpt4 book ai didi

c# - 在 UnhandledException 上显示消息对话框

转载 作者:行者123 更新时间:2023-11-30 21:34:55 26 4
gpt4 key购买 nike

在我的应用程序中,每当出现任何未处理的异常时,我都想显示一个消息对话框。但是似乎在抛出未处理的异常时没有出现对话框消息,显示消息弹出窗口是否有效?同样在 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();
}

最佳答案

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

关于c# - 在 UnhandledException 上显示消息对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49728543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com