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

C#.NetWindowsvb.netWinforms

C# Problem Overview


Following are the ways by which we can exit an application:

  1. Environment.Exit(0)
  2. Application.Exit()
  3. Form.Close()

What is the difference between these three methods and when to use each one?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

they are all fine. but form.Close() won't close your application it closes the form and after that the main-method returns an int (exitcode).

if you want that your application exits with exitcodes use Environmet.Exit(exitcode) or return the exitcode in the main-method

Solution 3 - C#

Dim forceExitTimer = New Threading.Timer(Sub() End, Nothing, 2500, Timeout.Infinite)
Application.Exit()

This method is perfect, allowing the software to close gently with application.exit before calling the brutal End command that will close the software by force

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParag MeshramView Question on Stackoverflow
Solution 1 - C#MartinStettnerView Answer on Stackoverflow
Solution 2 - C#codeteqView Answer on Stackoverflow
Solution 3 - C#orr burgelView Answer on Stackoverflow