What's Difference Between Environment.Exit() and Application.Shutdown()

what's difference between Environment.Exit() and Application.Shutdown()?

Environment.Exit() is a more brutal way of closing down your application, yes. But in general, if you need to kill your application to make it close then I think you're looking at the problem in the wrong way.
You should rather look into why the other threads aren't closing gracefully.

You could look into the FormClosing event on the main form and close down any resources that are hanging up the application, preventing it from closing.

This is how I have found resources hanging up the app.

  1. In debug mode, enable showing of threads. (This will allow you to see all the threads your application is running.)
  2. Close the application in the way that it does not close correctly.
  3. Press pause in Visual studio.
  4. Look at the threads list, and click on them to see where is the code they are hanging. Now that you can see what resources are blocking your application from closing, go to your FormClosing event and close/dispose them there.
  5. Repeat until the app closes correctly :)

Be aware that the threads list in debug mode will show some threads that are run but not under your control. These threads rarely have a name and when you click on them you get a message saying you have no symbols. These can be safely ignored.

One of the reasons for making sure your application is closing gracefully is that some resources (let's say a FileStream) are not done working, so using some API to force it to quit can make all sorts of "random" problems come in, like settings/data files not being written and so on.

What is the difference between Environment.Exit(0) and Environment.Exit(Environment.ExitCode)?

I've used both, and they seem to do the same thing.

As others have already noted, that's because the default value for ExitCode is 0.

So which one should I use?

Typically, if you call Exit(), you a) have a good reason for that and b) you want to terminate as soon as possible with all the disadvantages described in the remarks section.

Therefore you would

  • never call Environment.Exit(0); and instead let the void Main() method run to its end in a normal way.
  • never call Environment.Exit(Environment.ExitCode); because that would imply that the reason for the termination was set a while back.
  • call Environment.Exit(ERRORCODE);, likely with a meaningful constant instead of a magic number

So the real answer is: don't use it at all, if possible.

Instead you might want to try Window.Close() to close a single window or Application.Exit(), which closes all windows and gets you back to the Main() method and out of the Application.Run() method call.

If that's not sufficient to terminate your program and you still see it in Task Manager, it has a foreground thread running, e.g. a thread that saves the users work. You don't want to terminate that, because it could result in a corrupted file.

There is a concept of a boolean isRunning or _shouldStop variable to terminate threads.

If you don't know why your application is not terminating, attach a debugger and have a look at the callstack of the remaining threads.

Winforms: Application.Exit vs Environment.Exit vs Form.Close

The proper method would be Application.Exit(). According to the Documentation, it terminates all message loops and closes all windows thus giving your forms the possibility to execute their cleanup code (in Form.OnClose etc).

Environment.Exit would just kill the process. If some form has e.g. unsaved changes it would not have any chances to ask the user if he wants to save them. Also resources (database connections etc.) could not be released properly, files might not be flushed etc.

Form.Close just does what it says: it closes a form. If you have other forms opened (perhaps not now but in some future version of your application), the application will not terminate.

Keep in mind that if you use multithreading, Application.Exit() will not terminate your threads (and thus the application will keep working in the background, even if the GUI is terminated). Therefore you must take measures to kill your threads, either in the main function (i.e. Program.Main()) or when in the OnClose event of your main form.

Whats the difference between these methods for closing my application?

If you are wanting to gracefully handle the exception in the last case, that's ok (not great though) - as long is it is an exceptional situation to your application. Otherwise I'd create a new method that shows the form as a dialog with a boolean. If the boolean comes back false (aka, user closed the form) I would then handle the application shut down from there (Using Application.Exit()).

It is, in my humble opinion, very bad practice to close the application from a child rather than telling the parent. The only time I agree with this is in a FailFast situation, which are very rare.


  • Application.Exit();

This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread.

  • Application.ExitThread();

See above.


  • Environment.Exit(1);

Terminates this process and gives the underlying operating system the specified exit code.


  • Process.GetCurrentProcess().Kill();

Kill forces a termination of the process, while CloseMainWindow only requests a termination. When a process with a graphical interface is executing, its message loop is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system.


  • SFTPClient.LDAPLoggedIn = false; Close();

After the clarification in the comment (passes flow back to the parent and handles from there), this is by far the best way of doing this.


  • throw new Exception("User closed the form");

Throws an exception to the calling process. If this is the main thread, it will throw the exception in a very ugly way.

Application.Exit() vs Application.ExitThread() vs Environment.Exit()

Unfortunately, the problem isn't caused by any of these, and really exists (even if you don't get the message) in all of these scenarios.

Your problem is this:

On closing my WinForm App fires of a Form in Dialog mode. That form runs a Background worker that Syncs the DB with the remote DB and displays it's progress on the "Splash Form."

Since you're not actually shutting down when you request a shutdown, all of the "Exit" functions are trying to tear down your background thread. Unfortunately, this is probably happening in the middle of your DB sync, and an enumeration working in the save logic is probably providing that error.

I would recommend not using any of these - just call myMainForm.Close() instead. That should close your main form, which will fire your closing logic appropriately. Once the main form in your application closes, it will shut down gracefully.

Application.Exit and End diffrence

The End statement calls the Exit method of the Environment class in the 
System namespace. Exit requires that you have UnmanagedCode permission. If you
do not, a SecurityException error occurs.

reference: End statement

Effectively, End calls Environment.Exit which is immediate termination of the program. Whereas, Application.Exit processes pending messages before shutting down.

Application.Exit

Informs all message pumps that they must terminate, and then closes all 
application windows after the messages have been processed.

When should one use Environment.Exit to terminate a console application?

The only reason for calling Exit() as the last line of the Main method is if there might be other foreground threads running. They would stay running if execution just fell off the end of Main. Even in this case, it would usually be a better idea either to put in some explicit graceful termination into the other threads - or make them background threads to start with.

If you ever want to return a different exit code from Main, the simpler way to achieve that is to declare it to return int.

In short, I don't think you need Environment.Exit() here, and it's worth asking your colleagues exactly why they're using it - chances are they won't be able to give you a good reason, and it's another bit of fluff you can cut out.

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

  • Application.Exit() vs Application.ExitThread() vs Environment.Exit()
  • http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx


Related Topics



Leave a reply



Submit