Why would Application.Exit fail to work?

Try Environment.Exit(exitCode).


Having had this problem recently (that Application.Exit was failing to correctly terminate message pumps for win-forms with Application.Run(new Form())), I discovered that if you are spawning new threads or starting background workers within the constructor, this will prevent Application.Exit from running.

Move all 'RunWorkerAsync' calls from the constructor to a form Load method:

public Form()
{
  this.Worker.RunWorkerAsync();
}

Move to:

public void Form_Load(object sender, EventArgs e)
{
  this.Worker.RunWorkerAsync();
}

This is an article which expands on the same train of thought you are going through: http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/

Basically:

  • Environment.Exit - From MSDN: 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.

  • Application.Exit - From MSDN: 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. There are some more issues about this method, read about it in the MSDN page.

Another discussion of this: Link

This article points out 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)
{
  // Use this since we are a WinForms app
  System.Windows.Forms.Application.Exit();
}
else
{
  // Use this since we are a console app
  System.Environment.Exit(1);
}

Tags:

C#

.Net

Winforms