Terminating Your C# Application

Today I was doing some experimenting with some ideas and I created a console application to try things out in. From a certain function I started to type Application.Exit() and I quickly realized the rookie mistake. The Application class is part of the System.Windows.Forms namespace, and therefore, it's not the optimal way to terminate your console application. For that there is Environment.Exit(-1)... But this situation begs the question... what is the difference between the two statements:

System.Environment.Exit(-1);
System.Windows.Forms.Application.Exit();

They both get you what you want, which is to halt your application. But there are some differences between the two methods under the hood, according to the Microsoft documentation:

  • System.Environment.Exit(): Terminates the current process and gives the underlying operating system the specified exit code.
  • System.Windows.Forms.Application.Exit(): Informs all message loops that they must terminate, and then closes all application windows after the messages have been processed.

My take from this is that you always want to use Application.Exit() in a WinForms application in order to terminate things as gracefully as possible. In a console application you won't have the Application class available (unless you specifically import it) so just call Environment.Exit().

Also remember that there usually are several things you may want to do before terminating everything, such as persisting some objects, saving some settings, closing open files, etc. It is your responsibility to do those tasks before terminating... Provided you can control that and you are not crashing from an unhandled exception.

Comments

Comments powered by Disqus