[c#] Closing Applications

What is best practice when closing a C# application?

I have read that you can use:

Environment.Exit(0); or Application.Exit();

But what is the difference?

Furthermore, with regards to Environment.Exit(0), I have used exit codes before when working with Java but have never fully understood their purpose. What role do they play when exiting an application in C#?

This question is related to c#

The answer is


for me best solotion this is

 Thread.CurrentThread.Abort();

and force close app.


Application.Exit is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.

Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.

In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).

For more detail see the MSDN documentation.


What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.