End application after unhandled exception

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 an unhandled exception occurs, a lot of MessageBox appears on the screen (the exception occurs in a temporary procedure), and after closing one of them, Windows reports that there is an unhandled exception.

How can I avoid multiple MessageBoxes?
How can I avoid reporting an unhandled exception?
How can I terminate the application after an exception?
As you can easily assume, 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 a DispatcherUnhandledException. Is this necessary or is the code I wrote sufficient?

Thank.

+3
2

, boolean firstTime true :

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:

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

Application.Exit() System.Environment.Exit(exitCode), , .

+6

Source: https://habr.com/ru/post/1732857/


All Articles