Exiting .net application

There are few ways how to exit .net application.

Here are the most used:

  • Closing startup form or closing all forms (depends on project settings) – application should be exited by unloading all forms – this should be the preferred method.

    Shutdown mode in project properties

    Shutdown mode in project properties

  • Application.Exit method – closes all application windows after all exiting messages have been processed. This method doesn’t force the application to exit. FormClosing event is raised for all forms in OpenForms property and can be cancelled by setting FormClosingEventArgs.Cancel to true. Otherwise, FormClosed event is raised and then all running message loops and forms are closed.
  • Environment.Exit method – terminates application (even if there are threads running) and returns exit code to operating system. Requires UnmanagedCode security permission. When used within in Try-Catch block, Finally block is skipped. Should not be used in applications which havve a message loop and in any component assembly other than main.
  • END statement – forces entire application to stop running. Clears all application’s variables and closes all opened files. Doesn’t invoke Dispose or Finalize methods. When used within in Try-Catch block, Finally block is skipped. The END statement calls Environment.Exit method.
  • STOP statement – suspends execution. Like END statement, but doesn’t close files or clear any variables.

References: