Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic way to exit a .NET application

I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Environment.Exit(), etc.

I have an external "commons" library, and I'm trying to create a generic FailIf method that logs the failure to the logs, does this and that and this and that, then finally exits the application... here's a short version of it.

    public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
    {
        if (String.IsNullOrEmpty(message))
            throw new ArgumentNullException("message");

        if (fail)
        {
            //Do whatever I need to do

            //Currently Environment.Exit(exitCode)
            Environment.Exit(exitCode);
        }
    }

I have read that using Environment.Exit isn't the best way to handle things when it comes to WinForm apps, and also when working with WPF apps and Silverlight there are different ways to exit... My question is really:

What do I put to exit gracefully to cover all application types?

like image 611
michael Avatar asked Jan 20 '11 20:01

michael


2 Answers

Read this about the difference between using Environment and Application :

Application.Exit Vs Environment.Exit

There's an example of what you want to do in the bottom of that page:

if (System.Windows.Forms.Application.MessageLoop)
{
  // Use this since we are a WinForms app
  System.Windows.Forms.Application.Exit();
}
else
{
  // Use this since we are a console app
  System.Environment.Exit(1);
}
like image 109
Yochai Timmer Avatar answered Nov 15 '22 17:11

Yochai Timmer


If it's just an abort, use Environment.Exit(). If it's something very critical (that can't handle any sort of cleanup), use Environment.FailFast().

like image 34
user541686 Avatar answered Nov 15 '22 17:11

user541686