Geeks With Blogs

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

.NET Hobbyist Programmer Staying Confused in a Busy World

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

Posted on Sunday, June 6, 2004 1:40 PM Programming | Back to top


Comments on this post: Application.Exit vs. Environment.Exit

# re: Application.Exit vs. Environment.Exit
Requesting 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()
Try
Application.Run(New Form1)

Catch ex As Exception
'Log the exception information

Finally
'clean up after ourselves

End Try

End Sub
End Class
Left by David Totzke on Jun 06, 2004 3:48 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Mark Treadwell on Jun 06, 2004 4:27 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.

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

Left by David Totzke on Jun 06, 2004 5:34 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Mark on Jun 06, 2004 5:54 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Mark on Jun 06, 2004 5:59 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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 !?
Left by wave on Oct 08, 2004 4:18 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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...
Left by JF Delges on Apr 20, 2005 8:13 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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()
Left by philosophisticated on Jun 15, 2005 7:09 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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 ...
Left by Frank Bergmann on Oct 11, 2005 3:16 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
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...
Left by Ted on Nov 11, 2005 10:28 AM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
Okay, here's a stupid question:
what's the best method for closing out all forms in my application without referencing them directly?
Left by Jeff Lowery on Dec 02, 2005 4:52 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
how can clear fields in a form
Left by praveen on Dec 04, 2005 1:09 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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..
Left by Siddharth on May 02, 2006 3:13 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Ahmad on Jan 11, 2007 2:10 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
Can't u just set the fields like in JAVA setTextFieldName = "" - Or something like that?
Left by mox on Apr 14, 2007 2:08 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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
Left by Taoge on Apr 18, 2007 9:42 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
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);
Left by Kris on May 29, 2007 3:03 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
How to kill the process (application) inside the .dll when hitting system error withing .dll?
Left by kien on Oct 31, 2007 7:10 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
For Ted , even though its been 2 years. To restart the application don't use Exit(), use Restart() :)
Left by Zach on Feb 06, 2008 1:10 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
Lot of thanks. That System.Environment.Exit(exitCode) helped me too much!
Left by Niau on May 12, 2008 6:18 PM

# plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz help
Requesting Gravatar...
does anyone know how to write exit code in visual basic 9?
Left by elnaz on Jun 17, 2008 5:03 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
I always use Environment.Exit(0).
Left by Propeng on Jul 12, 2008 10:53 AM

# Doing the same here
Requesting 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?
Left by Ignacio Soler on Sep 18, 2008 3:52 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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 application.run() so, i find use Environment.Exit() is the quit method.
Left by long_long china on Oct 05, 2008 11:37 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Schmuli on Nov 30, 2008 10:28 AM

# shutdown pc
Requesting 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
Left by hassan on Jan 13, 2009 2:54 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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 ?
Left by Awadhesh on Jan 15, 2009 2:07 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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
Left by Sumit on Feb 05, 2009 1:11 AM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
thanks man. I'm embarrassed i had to google this to find out how to bloody exit my C# app. :(
Left by Free cursors on Mar 09, 2009 8:28 PM

# re: Application.Exit vs. Environment.Exit
Requesting Gravatar...
Application.Exit does not exists anymore when working with WPF :)
Left by Kristof on Mar 12, 2009 6:52 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.

Thanks,
Steve
Left by Steve on Mar 26, 2009 10:52 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by Som on Mar 26, 2009 2:09 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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.
Left by majo on Oct 06, 2009 9:48 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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!
Left by Josh on Nov 21, 2010 12:42 PM

# re: Application.Exit vs. Environment.Exit
Requesting 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).
Left by Grahame Armitage on Jun 29, 2012 5:25 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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
Left by R Simmons on Aug 01, 2012 4:06 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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:

http://www.ilearnttoday.com/tag/environment-exit0

Natalie
Left by Natalie on Sep 10, 2012 9:25 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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
Left by sagar on Mar 03, 2014 7:30 AM

# re: Application.Exit vs. Environment.Exit
Requesting 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
Left by sagar on Mar 03, 2014 7:34 AM

Your comment:
 (will show your gravatar)


Copyright © Mark Treadwell | Powered by: GeeksWithBlogs.net | Join free