.NET Hobbyist Programmer

Staying Confused in a Busy World
posts - 251, comments - 157, trackbacks - 703

My Links

News

Neat Stuff Read all my hurricane entries While you are here, visit the Geeks With Blogs main feed
Advertising
Links Status of the Navy
Channel 9

Tag Cloud

Article Categories

Archives

Post Categories

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:

  System.Environment.Exit(-1)
  System.Windows.Forms.Application.Exit()
  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
  System.Windows.Forms.Application.Exit()
}
Else
{
  // Use this since we are a console app
  System.Environment.Exit(1)
}

Print | posted on Sunday, June 06, 2004 1:40 PM | Filed Under [ Programming ]

Feedback

Gravatar

# re: Application.Exit vs. Environment.Exit

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()
Try
Application.Run(New Form1)

Catch ex As Exception
'Log the exception information

Finally
'clean up after ourselves

End Try

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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.

http://www.microsoft.com/downloads/details.aspx?FamilyID=8ca8eb6e-6f4a-43df-adeb-8f22ca173e02&displaylang=en

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

Thanks I appreciate the information. Coming from the C/C++ world, I often find the tons of possible methods to do one thing confounding, especially given the lack of documentation. Yes I know they have a ton of it, but they do not discuss the differences, why use one over the other. I also wish the documentation would cross refernce each other. Like the 3 different exits should refernce each other. Or even an old school to new methods translator.
3/29/2005 1:18 PM | Mike
Gravatar

# re: Application.Exit vs. Environment.Exit

# 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
Gravatar

# Environment.Exit

Hier findet sich ein kurzer Vergleich zwischen System.Windows.Forms.Application.Exit und System.Environment.Exit. Ich bin gerade dabei, einen Service unter .net entwickeln und habe nach einer Möglichkeit gesucht, mein Programm "sauber" bei einem Fehler in
5/23/2005 5:12 AM | nodomain.cc
Gravatar

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

This is a long-lasting thread =)

I have the same problem as
6/15/2005 7:09 AM by philosophisticated
and
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):
---
Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath);
---

However, this WON'T work:
-------
Environment.Exit(0);
System.Diagnostics.Process.Start(Application.ExecutablePath);
--------

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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

e.g.
System.Diagnostics.Process.Start(System.Windows.Forms.Application.ExecutablePath);
System.Environment.Exit(0);
5/29/2007 3:03 PM | Kris
Gravatar

# re: Application.Exit vs. Environment.Exit

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

# re: Application.Exit vs. Environment.Exit

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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

# plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz help

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

# re: Application.Exit vs. Environment.Exit

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

# Doing the same here

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
Gravatar

# re: Application.Exit vs. Environment.Exit

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 application.run() so, i find use Environment.Exit() is the quit method.
10/5/2008 11:37 PM | long_long china
Gravatar

# re: Application.Exit vs. Environment.Exit

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

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 8 and 2 and type the answer here:

Powered by: