问题描述
我在WPF应用程序中有问题。我写了这段代码: public partial class App:Application
{
public App ()
{
AppDomain.CurrentDomain.UnhandledException + = new
UnhandledExceptionEventHandler(MyHandler);
}
void MyHandler(object sender,UnhandledExceptionEventArgs e)
{
异常异常= e.ExceptionObject为异常;
MessageBox.Show(exception.Message,ERROR,
MessageBoxButton.OK,MessageBoxImage.Error);
}
...
}
但是当一个未处理的异常发生时,很多MessageBox出现在屏幕上(异常发生在定时例程中),并且在关闭其中一个异常后,Windows发出一个未处理的异常。
如何避免多个MessageBox?
如何避免未处理异常的消息?
如何在异常之后终止应用程序?
可以很容易地假设,我想显示一条消息(但只有一个)与我的MessageBox,然后终止应用程序没有任何其他消息。
在一个上一个问题,告诉我要使用DispatcherUnhandledException。是否有必要或我写的代码是否足够?
谢谢。
您可以通过将静态布尔值 firstTime
初始化为 true
并使用异常处理程序中的代码来避免多个消息框: / p>
void MyHandler(object sender,UnhandledExceptionEventArgs e)
{
if(firstTime){
异常异常= e.ExceptionObject为异常;
MessageBox.Show(exception.Message,ERROR,
MessageBoxButton.OK,MessageBoxImage.Error);
firstTime = false;
} else {
//现在杀死进程....
}
}
要终止进程,请在 MyHandler
中:
系统.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
proc.Kill();
I have a problem in a WPF application. I wrote this code:
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);
}
...
}
but when a unhandled exception happens, a lot of MessageBox appear to the screen (the exception happens in a timed routine) and after closing one of them, Windows signals that there is an unhandled exception.
How can I avoid multiple MessageBoxes?
How can I avoid the message of an unhandled exception?
How can I terminate the application after the exception?
As you can easily suppose, I would like to show a message (but only one) with my MessageBox and then terminate the application without any other message.
In a previous question related to this argument, Kyle Rozendo told me to use DispatcherUnhandledException. Is it necessary or the code I written is sufficient?
Thank you.
You can avoid multiple messageboxes by initializing a static boolean firstTime
to true
and use the code within the Exception handler:
void MyHandler(object sender, UnhandledExceptionEventArgs e) { if (firstTime){ Exception exception = e.ExceptionObject as Exception; MessageBox.Show(exception.Message, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); firstTime = false; }else{ // Now kill the process.... } }
To terminate the process do this, within the MyHandler
:
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess(); proc.Kill();
这篇关于在未处理的异常后终止应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!