Forum guidelines
Application.Exit vs Application.Shutdown vs Environment.Exit
Posted By Suthish Nair on 09 Mar 2011




 Can anyone list the advantages/disadvantages of above methods.
 When to use, how to use etc..

 Dont post any links or copy paste, this for knowledge sharing from persons who already  experienced with above methods.



Answer helped you, Mark as Answer?
  • 0
  • 0
Re: Application.Exit vs Application.Shutdown vs Environment.Exit
Posted By Vulpes on 09 Mar 2011   Accepted Answer
Application.Exit() is for exiting a windows forms application in a graceful way. Basically, it stops the message pump, closes all windows and lands you back in the Main() method just after the call to Application.Run(). However, sometimes it doesn't appear to work - this is usually because there are other foreground threads (apart from the UI thread) still running which are preventing the thread from ending.

Application.Shutdown() is (broadly) the equivalent of Application.Exit() in a WPF application. However, you have a bit more control as you can set the ShutDownMode so that the application shuts down when the main window closes, the last window closes or only when this method is called. 

Environment.Exit() kills all running threads and the process itself stone dead. This should only be used in WF or WPF as a last resort when the more graceful methods are not working for some reason. It can also be used to make an abrupt exit from a console application.

Re: Application.Exit vs Application.Shutdown vs Environment.Exit
Posted By Sam Hobbs on 10 Mar 2011  
They are essentially for getting out of a program that is messed up and the programmer does not know how to get out or at least not safely. Environment.Exit(exitCode) for a console program might be for getting out normally and returning an exit code; I am not sure.

Thinking is a feeling; pleasant for some and unpleasant for others.
Re: Application.Exit vs Application.Shutdown vs Environment.Exit
Posted By Vulpes on 10 Mar 2011  
If you want to exit from a console program but return an exit code to the operating system (other than the default of zero), then the usual way is to use one of the patterns for the Main() method which return an int:

static int Main()

   if (someErrorHasOccurred) return 1; // say

   return 0;

Environment.Exit(1) would achieve the same result but is best restricted to situations where an abrupt exit is needed because it's difficult or impossible to get back to the Main() method to exit gracefully. 

C# Corner Annual Conference 2016


Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.