Generic way to exit a .NET application

31,280

Solution 1

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

Solution 2

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().

Share:
31,280
michael
Author by

michael

Updated on September 11, 2020

Comments

  • michael
    michael over 3 years

    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?