End Application in C #

343 Views Asked by At

As a sample below, I am using an If statement for my Application, where if you press Yes, the Application should close. I click Yes, and No, and the Application just continues regardless. Does anyone know why this might happen?

if (diff_ULNDOB.Any())
{
     DialogResult result1 = System.Windows.Forms.MessageBox.Show("Cannot proceed with Cross Year checks! Please see Workbook " + output + "." + " Do you wish to close the Application?", "Error",
     MessageBoxButtons.YesNo);

    if (result1 == DialogResult.Yes)
    {
       System.Windows.Forms.Application.Exit();           
    }

    Progress.Error = true;
    break;
}
2

There are 2 best solutions below

0
On BEST ANSWER

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

2
On

I would use Application.Exit() as this is a cleaner way of doing it than Environment.Exit(0).

The advantages of using Application.Exit() is that is will allow the form to execute any cleanup processes like Form.OnClose which can include closing database connections and file handlers.

Enivornment.Exit(0) is the same as just directly killing the process, so if you use it make sure all connections and files have been released properly.


Above was for Windows Forms applications. If it is a console application, the best way of exiting the application is returning the relevant exit code in the Main method.