Blog Stats
  • Posts - 276
  • Articles - 2
  • Comments - 311
  • Trackbacks - 660


Application.Exit vs. Environment.Exit

While refining my unhandled exception handler code, I wandered into this question.  What is the real difference between the following three statements:

  End ' Visual Basic only

They can all get you to where you want to go, application shutdown, but when is each appropriate?  There is a brief bit buried in the C# FAQ.  Looking through the Microsoft help is not particularly helpful, but it does give you the rigorous description of what each does.

  • 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 WinForms 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.
  • End - (Visual Basic only)  Terminates execution immediately.  The End statement can be placed anywhere in a procedure to end code execution, close files opened with an Open statement, and clears variables at module and class level and all static local variables in all modules.  The End statement calls System.Environment.Exit.  The End statement stops code execution abruptly, without invoking the Finalize method or any other Visual Basic code.  Object references held by other programs are invalidated.  The End statement provides a way to force your program to halt.  For normal termination of a Visual Basic program, you should unload all forms.  Your program closes as soon as there are no other programs holding references to objects created and no code executing.

What do you do in a reusable library when you do not know how it will be used?  First, in a VB program, do not use End.  This will likely lead to undesireable results.

You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property.  If true, then Run has been called and you can assume that a WinForms application is executing as follows.

If (System.Windows.Forms.Application.MessageLoop)
  // Use this since we are a WinForms app
  // Use this since we are a console app


# re: Application.Exit vs. Environment.Exit

Gravatar Frankly, a component library shoud not be able to force your application to exit. That's just wrong. If you run into an error that is going to require termination, you should bubble the exception up to the main try...catch block you have around your main message loop. You do have one don't you?

I'm not sure how this is going to look so forgive me if it's a dog's breakfast :-)

'Go to Project --> Properties --> Common Properties --> General
'Set the Startup Object to the StartUp class
Public Class StartUp

'provide a Shared Main method
Public Shared Sub Main()
Application.Run(New Form1)

Catch ex As Exception
'Log the exception information

'clean up after ourselves

End Try

End Sub
End Class
6/6/2004 3:48 PM | David Totzke

# re: Application.Exit vs. Environment.Exit

Gravatar I am still playing with this, but the DLL holds the unhandled exception handlers, Assert handler, custom dialogs, etc. If the CLR throws an unhandled exception, or even my code, or an exception occurs in the exception handler, I think I want to shut everything down after recording the error. 6/6/2004 4:27 PM | Mark Treadwell

# re: Application.Exit vs. Environment.Exit

Gravatar Check out the Exception Handling Application Block from MS. It's done all of this work for you. At the very least, it can give you some ideas on how to proceed with your own version.

6/6/2004 5:34 PM | David Totzke

# re: Application.Exit vs. Environment.Exit

Gravatar I am familiar with the Application Blocks, but I am not interested in the publishing side of exception management which the EMAB and EIF excel at. I am working through the logic I want to execute after publishing/logging is done. The unhandled exception handler is non-trivial and I am learning as I go - which is one of the points of the exercise. The EMAB does not address what you should do with an unhandled exception, although several blogs and MSDN articles recommend shutting the application down. That is what I am working on. 6/6/2004 5:54 PM | Mark

# re: Application.Exit vs. Environment.Exit

Gravatar David: One other answer to an earlier question you posed. Yes I have a message loop in most applications, but a console app does not necessarily use one. I am writing code which will handle that situation. 6/6/2004 5:59 PM | Mark

# re: Application.Exit vs. Environment.Exit

Gravatar In my C# window application I create a thread then when I call and use Application.Exit it ends the application but threads is continuing tu work. (shouldnt it end?). So I call instead Environment.Exit(0) and it(thread) stop at the same time application stops. Why !? 10/8/2004 4:18 AM | wave

# re: Application.Exit vs. Environment.Exit

Gravatar # re: Application.Exit vs. Environment.Exit 10/8/2004 4:18 AM wave

In my C# window application I create a thread then when I call and use Application.Exit it ends the application but threads is continuing tu work. (shouldnt it end?). So I call instead Environment.Exit(0) and it(thread) stop at the same time application stops. Why !?

I have the same problem... 4/20/2005 8:13 AM | JF Delges

# re: Application.Exit vs. Environment.Exit

Gravatar Thanks a lot for this article.
I have an application in which i create a thread. And i was unable to stop it with application.exit()
Now i use environment.exit()
6/15/2005 7:09 AM | philosophisticated

# re: Application.Exit vs. Environment.Exit

Gravatar In order to make a WinForm Application end your threads at Application.Exit() just do some cleanup in an Exit-evenenthander ... see

Application.ApplicationExit+=new EventHandler(...)

But ... what to do in Console applications ... 10/11/2005 3:16 PM | Frank Bergmann

# re: Application.Exit vs. Environment.Exit

Gravatar This is a long-lasting thread =)

I have the same problem as
6/15/2005 7:09 AM by philosophisticated
3/29/2005 1:18 PM by Mike

What Frank posted 11 Oct isn't really a good option in my opinion. To write code for cleaning up all those threads scattered throughout the program isn't reasonable. I have many threads in different parts of the program, and I try to separate them so that they are as "standalone" as possible.
Therefore, a single class/method does not have access to them all.

So, in my case I use Environment.Exit() aswell - that works fine.

My problem today is that I need a reboot-mechanism for my program. This will "reboot" it (well, not really since Application.Exit() doesnt kill the app):

However, this WON'T work:

After Environment.Exit(0) has been called the program is dead and no reboot is made... 11/11/2005 10:28 AM | Ted

# re: Application.Exit vs. Environment.Exit

Gravatar Okay, here's a stupid question:
what's the best method for closing out all forms in my application without referencing them directly? 12/2/2005 4:52 PM | Jeff Lowery

# re: Application.Exit vs. Environment.Exit

Gravatar how can clear fields in a form 12/4/2005 1:09 AM | praveen

# re: Application.Exit vs. Environment.Exit

Gravatar Hi..
I have a VB application which invokes a DOS based exe file (application).. my question is.. how do terminate the dos application thru the VB form without terminating the VB form..

If anyone knows this.. plz reply quickly.. its realy urgent..

Thanx.. 5/2/2006 3:13 PM | Siddharth

# re: Application.Exit vs. Environment.Exit

Gravatar I have a situation where I have a console Application calling into a WebService. If the WebService throws an exception the Console Application doesnt Exit properly even though I have a main exception handler. Why in the first place I need to use Environment.Exit(1) in the first place. 1/11/2007 2:10 PM | Ahmad

# re: Application.Exit vs. Environment.Exit

Gravatar Can't u just set the fields like in JAVA setTextFieldName = "" - Or something like that? 4/14/2007 2:08 PM | mox

# re: Application.Exit vs. Environment.Exit

Gravatar I have the same problem as JF Delges. When using Application.Exit(), the process is still going, if debug in IDE, the debug process is still running. Using Environment.Exit, everything is ok.
I'm using C# 2005 Express 4/18/2007 9:42 PM | Taoge

# re: Application.Exit vs. Environment.Exit

Gravatar Ted:
Start the new application BEFORE closing the first one.

System.Environment.Exit(0); 5/29/2007 3:03 PM | Kris

# re: Application.Exit vs. Environment.Exit

Gravatar How to kill the process (application) inside the .dll when hitting system error withing .dll? 10/31/2007 7:10 PM | kien

# re: Application.Exit vs. Environment.Exit

Gravatar For Ted , even though its been 2 years. To restart the application don't use Exit(), use Restart() :) 2/6/2008 1:10 PM | Zach

# re: Application.Exit vs. Environment.Exit

Gravatar Lot of thanks. That System.Environment.Exit(exitCode) helped me too much! 5/12/2008 6:18 PM | Niau

# plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz help

Gravatar does anyone know how to write exit code in visual basic 9? 6/17/2008 5:03 PM | elnaz

# re: Application.Exit vs. Environment.Exit

Gravatar I always use Environment.Exit(0). 7/12/2008 10:53 AM | Propeng

# Doing the same here

Gravatar Hello, I'm doing the same here. I've developed a generic exception handling DLL with a custom exception dialog with some options, one of these options is to end the application but Application.Exit() is not working dont know why.

As the Unhandled event handler is located always at the main application form I tryed to Close the main form thru the owner property of the exception dialog without success.

Any hint about that Mark? 9/18/2008 3:52 AM | Ignacio Soler

# re: Application.Exit vs. Environment.Exit

Gravatar this question is very interesting ! In one of my programs I want to quit the process and don't show message i use Application.Exit() first time , but before the process end there some messages are showed what i don't want to see. look for so long time , i find the messages what showed is before the so, i find use Environment.Exit() is the quit method. 10/5/2008 11:37 PM | long_long china

# re: Application.Exit vs. Environment.Exit

Gravatar Hi!

I know its been more than four years since you mentioned this, but it is something that keeps coming up, I guess.

The application that I've got does some instantiation in the constructor of the object passed to Application.Run(), most notably, starting a WCF ServiceHost. If this fails, I display a message and then I want to terminate the application. I can't use Application.Exit(), because this all happens before Application.Run, so there isn't a message loop to terminate. When the constructor returns, the next line is Application.Run(), causing the application to remain in debug mode. I therefore used Environment.Exit() in this case.
Perhaps I should move the code from the constructor, however, I don't have much choice as to where else to put it instead. 11/30/2008 10:28 AM | Schmuli

# shutdown pc

Gravatar plz any one tell me that how can shutdown our pc on button click in c# window application plz send me mail if u khnow it plz 1/13/2009 2:54 PM | hassan

# re: Application.Exit vs. Environment.Exit

Gravatar MSDN syas Environment.exit Terminates this process and gives the underlying operating system the specified exit code.
Does it mean it also terminates all new processes / threads started from this process ? 1/15/2009 2:07 AM | Awadhesh

# re: Application.Exit vs. Environment.Exit

Gravatar But in my windows form application several time executable doesn't disaappear from taskmanager after doing Application.Exit() . and hence i cant create an other instance of my application. if i use environment.exit(-1), exe doesnt disappear from taskmanager but i m able to create new instance of application. my code is like that only one instance can be create of application 2/5/2009 1:11 AM | Sumit

# re: Application.Exit vs. Environment.Exit

Gravatar thanks man. I'm embarrassed i had to google this to find out how to bloody exit my C# app. :( 3/9/2009 8:28 PM | Free cursors

# re: Application.Exit vs. Environment.Exit

Gravatar Application.Exit does not exists anymore when working with WPF :) 3/12/2009 6:52 PM | Kristof

# re: Application.Exit vs. Environment.Exit

Gravatar What is the differnce between - Evironment.Exit(0 or 1).. 0/1 = Main Thread ?? 2 or 3 or others would mean a child thread ??

Also, what would be the best way to restart a service after the exit code has been executed.

Responses Appreciated.

Steve 3/26/2009 10:52 AM | Steve

# re: Application.Exit vs. Environment.Exit

Gravatar Steve,

That int argument to the Environment.Exit is the exit code. 0 is the default value. If you use this in a console application, you can use ECHO %ERRORLEVEL% to check the value. 3/26/2009 2:09 PM | Som

# re: Application.Exit vs. Environment.Exit

Gravatar Normally you run your application in loop routine like while(true) or something like that; then when you read the key pressed over Console.ReadLine; you try to get out if the pressed key is exactly what you want to quit the application, it fhis is the case you just call "break"; to break the loop and it's done, your application exits.

If this is not what you wanted to ask for, then give some more details. 10/6/2009 9:48 AM | majo

# re: Application.Exit vs. Environment.Exit

Gravatar I was looking everywhere for something like this.

"System.Windows.Forms.Application.Exit()" would not stop it immediately, but "System.Environment.Exit(-1)" works perfectly.

Thanks! 11/21/2010 12:42 PM | Josh

# re: Application.Exit vs. Environment.Exit

Gravatar In our app I've found that Application.Exit() should be called if displayed as a WinForm whist [Mock]Unit Tests require Environment.Exit(0). 6/29/2012 5:25 AM | Grahame Armitage

# re: Application.Exit vs. Environment.Exit

Gravatar I have a similar problem in PocketPC (2005)
I have used Application.exit for years and it does what you say stops the app
Now all of a sudden a new app which rins in the same set of class libraries leaves the exe open
Environment.exit does not appear to be avaialble in PocketPC
Any ideas please 8/1/2012 4:06 AM | R Simmons

# re: Application.Exit vs. Environment.Exit

Gravatar The best method to use is Environment.Exit(int returnCode).

This helps you even to return a code to the OS.

This guy has a good brief explanation to it:

9/10/2012 9:25 AM | Natalie

# re: Application.Exit vs. Environment.Exit

Gravatar I am suffering a problem with application.Exit()
actual problem is when i am close my application it s runs on process How to Close application and ReOpen
3/3/2014 7:30 AM | sagar

# re: Application.Exit vs. Environment.Exit

Gravatar Hi,

There are probably many reasons for this but when I close my application it continues to run as a process in Task Manager. This then causes a problem when I start the app. again, as it's still running from the previous time.
Where can I begin, to find out why it continues to run and fails to shut down poperly when I exit the app.?

Thanks 3/3/2014 7:34 AM | sagar

Post A Comment



Copyright © Mark Treadwell