Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best practice to exit an WPF application?

Tags:

c#

wpf

exit

I am maintaining an existing C# application, and I noticed the following code are not working as expected.

        private void Form1_Load(object sender, EventArgs e){
             ...
            if (proc.Length == 0)
            {                    
                proc = Process.GetProcessesByName("OpCon");
                if (proc.Length == 0)
                {
                    WriteLog("DataloggerService start: no TSS process detected; close;");
                    this.Close();
                }
            }
          ...
         }

The code is supposed to exit after the Close() api call. However, it still proceed.

After some reading and research, I modified it to

       private void Form1_Load(object sender, EventArgs e){
            ....
            if (proc.Length == 0)
            {                    
                proc = Process.GetProcessesByName("OpCon");
                if (proc.Length == 0)
                {
                    WriteLog("DataloggerService start: no TSS process detected; close;");
                    this.Dispose();
                    Environment.Exit(0);
                }
            }
            ....
        }

It seems to exit as expected. However, I am not confident whether this is the best practice?

is it really necessary to call this.Close() or this.Dispose() before Environment.Exit()?

Thanks.

regards, Sqr

like image 261
sqr Avatar asked Oct 16 '14 02:10

sqr


People also ask

How do I close a WPF application?

We can close the window either by using "this. Close()"or by using "App. Current. Shutdown()".

How do I close all Windows in WPF?

The proper way to shutdown a WPF app is to use Application. Current. Shutdown() . This will close all open Window s, raise some events so that cleanup code can be run, and it can't be canceled.

Is WPF still in demand?

WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).


1 Answers

In your WPF application whenever your MainWindow that is specified as StartupURI in App.xaml is closed your application exits automatically.

Still if you want to handle this exit of application on your end you can go for below solution.

Override the onClosing of MainWindow and manually exit/shutdown your application.

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    // Shutdown the application.
    Application.Current.Shutdown();
    // OR You can Also go for below logic
    // Environment.Exit(0);
}
like image 156
jadavparesh06 Avatar answered Oct 22 '22 06:10

jadavparesh06