Mau*_*lli 3 c# wpf exception-handling
我在WPF应用程序中遇到问题.我写了这段代码:
public partial class App : Application
{
public App()
{
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(MyHandler);
}
void MyHandler(object sender, UnhandledExceptionEventArgs e)
{
Exception exception = e.ExceptionObject as Exception;
MessageBox.Show(exception.Message, "ERROR",
MessageBoxButton.OK, MessageBoxImage.Error);
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是当一个未处理的异常发生时,很多MessageBox出现在屏幕上(例外情况发生在定时例程中),关闭其中一个后,Windows发出一个未处理的异常信号.
如何避免多个MessageBoxes?
如何避免未处理异常的消息?
如何在异常后终止应用程序?
您可以轻松地假设,我想用MessageBox显示一条消息(但只有一条),然后在没有任何其他消息的情况下终止应用程序.
在之前与此论点相关的问题中,Kyle Rozendo告诉我使用DispatcherUnhandledException.是否有必要或我编写的代码是否足够?
谢谢.
在显示错误对话框后,您还可以使用Application.Exit()或System.Environment.Exit(exitCode)立即关闭应用程序.
您可以通过初始化静态布尔值并使用异常处理程序中的代码来避免多个消息firstTime框true:
void MyHandler(对象发送者, UnhandledExceptionEventArgs e)
{
如果(第一次){
异常异常 = e.ExceptionObject 作为异常;
MessageBox.Show(异常.Message, "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
第一次=假;
}别的{
// 现在终止进程....
}
}
要终止进程,请在以下位置执行此操作MyHandler:
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess(); proc.Kill();