How to Properly Exit a C# Application

How do I properly exit a C# application?

From MSDN:

Application.Exit

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This is the code to use if you are have called Application.Run (WinForms applications), this method stops all running message loops on all threads and closes all windows of the application.

Environment.Exit

Terminates this process and gives the underlying operating system the specified exit code. This is the code to call when you are using console application.

This article, Application.Exit vs. Environment.Exit, points towards a good tip:

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) 
{
// WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Console app
System.Environment.Exit(1);
}

Reference: Why would Application.Exit fail to work?

How to exit a Windows Forms Application in C#

You first need to quote your string so the message box knows what to do, and then you should exit your application by telling the application context to exit.

private void Defeat()
{
MessageBox.Show("Goodbye");
Application.Exit();
}

Application.Exit() not working properly

The code inside Music_FormClosing is preventing your application from exiting. To get the desired behavior (prevent the user closing the music form), you can utilize the FormClosingEventArgs CloseReason property:

private void Music_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
e.Cancel = true;
}

End Application in C #

Add Environment.Exit(0); when you want to close your application.

Application.Exit

Application.Exit really just asks the message loop very gently.

If you want your app to exit, the best way is to gracefully make it out of Main, and cleanly close any additional non-background threads.

If you want to be brutal... Environment.Exit or Environment.FailFast? note this is harsh - about the same as killing your own Process.



Related Topics



Leave a reply



Submit