The correct way to close the WPF GUI application is: GetCurrentProcess (). Kill (), Environment.Exit (0) or this.Shutdown ()

My WPF 4.0 GUI (C # .Net 4.0) with GUI works with a SQL Server database. Each time I run my application, it creates a connection to SQL Server through the ADO.NET Entity Framework, and if SQL Server is unavailable, it throws an exception and displays a MessageBox with a notification.

Now I want the application to close after the user has read this message. I found three ways to do this:

Process.GetCurrentProcess().Kill(); 

or

 this.Shutdown(); // Application.Current.Shutdown() 

or

 System.Environment.Exit(0); 

They all work fine and do what I need to do - close the application and kill the application process in the Windows task manager.

I want to know:

  • What is the difference between the two?
  • Which way will close my application faster?
  • Which way to close the application should be used?
  • Is Application.Current.Shutdown() and this.Shutdown() the same way to close the application?

Or maybe there is another, more appropriate way to close the WPF GUI application?

Application.Exit() does not work for me, as I get an error:

The ' System.Windows.Application.Exit ' event can only be displayed on the left side + + or - =

Thank.

+48
c # database exception-handling wpf
Oct 07 '10 at 10:44
source share
4 answers

Application.Current.Shutdown() is the right way to disable the application. Generally, because fire exit events that you can handle more

Process.GetCurrentProcess().Kill() should be used when you want to kill an application. more details

Ad1. The nature of these methods is completely different. The shutdown process may be paused to complete some operations to cause the application to close.

Ad2. Kill() will probably be the fastest way, but it's a bit of a kernel panic.

Ad3. Shutdown because it fires a close event

ad4. It depends on what this .

+67
07 Oct '10 at 11:14
source share

Use Application.Current.Shutdown ();

Add ShutdownMode = "OnMainWindowClose" to App.xaml

+2
Dec 13 '15 at 17:22
source share
 private void ExitMenu_Click(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } 
+1
May 23 '16 at 16:07
source share

@Damian Leszczyński - Your answer pretty much covers the 4 specific questions you asked. For your last question on Application.Exit() , this is an event you can subscribe to, not a method you can call. It should be used as follows:

 Application.Current.Exit += CurrentOnExit; //this.Exit += CurrentOnExit; would also work if you're in your main application class ... private void CurrentOnExit(object sender, ExitEventArgs exitEventArgs) { //do some final stuff here before the app shuts down } 
0
Oct 18 '16 at 14:25
source share



All Articles