终止未处理的异常后,应用程序 [英] Terminate application after unhandled exception

查看:182
本文介绍了终止未处理的异常后,应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF应用程序有问题。我写了这个代码:

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

    ...
}



但是当一个未处理的异常情况发生时,有很多消息框出现在屏幕(例外发生在定时例程)和关闭其中一人之后,Windows信号,有未处理的异常。


我怎样才能避免多次提示消息框?

我怎样才能避免未处理的异常?

我怎么能例外后终止应用程序的消息?

你可以很容易地想,我想用我的MessageBox显示一条消息,(但只有一个),然后没有任何其他消息终止应用程序。


在< A HREF =htt​​p://stackoverflow.com/questions/2251868/unhandled-exception>上一个问题相关这种说法,的凯尔Rozendo 告诉我使用DispatcherUnhandledException。是否有必要或我编写的代码就足够了?


谢谢你。

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.

推荐答案

您可以通过初始化静态布尔避免多次提示消息框 firstTime 真正和使用异常处理程序中的代码:

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....
   }
} 

要终止的进程做到这一点, MyHandler的中:

To terminate the process do this, within the MyHandler:


System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
proc.Kill();

这篇关于终止未处理的异常后,应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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