Right way to close WPF GUI application: GetCurrentProcess().Kill(), Environment.Exit(0) or this.Shutdown()

僤鯓⒐⒋嵵緔 提交于 2019-11-30 07:02:34

问题


My GUI desktop-based WPF 4.0 (C# .Net 4.0) program works with SQL Server database. Each time when I run my application it creates a connection to SQL Server via ADO.NET Entity Framework and if SQL Server is not reachable it throws an exception and shows MessageBox with notification.

Now I want that after user read this message application will shut down. I found three ways to do this:

Process.GetCurrentProcess().Kill();

or

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

or

System.Environment.Exit(0);

All of them work fine and do what I need — close application and kill application's process in Windows Task Manager.

I want to know:

  1. What is the difference between them?
  2. Which way will close my application faster?
  3. Which way to close application should I use?
  4. Is Application.Current.Shutdown() and this.Shutdown() the same way to close application?

Or maybe there is another, more suitable, way to close a WPF GUI application?

Application.Exit() doesn't work for me as I get the error:

The event 'System.Windows.Application.Exit' can only appear on the left-hand side of += or -=

Thanks.


回答1:


Application.Current.Shutdown() is the proper way to shutdown an application. Generally because fire the exit events that you can handle more

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

Ad1. The nature of those methods are totally different. The shutdown process can be paused to end some operations, kill force the application to close.

Ad2. Probably Kill() will be the fastest way, but this is something like kernel panic.

Ad3. Shutdown because it fires the close event

Ad4. That depend what this is.




回答2:


Use Application.Current.Shutdown();

Add ShutdownMode="OnMainWindowClose" in App.xaml




回答3:


private void ExitMenu_Click(object sender, RoutedEventArgs e)
    {
        Application.Current.Shutdown();
    }



回答4:


@Damian Leszczyński - Vash's answer pretty much covers the 4 specific questions you asked. For your final question on Application.Exit(), that's an event you can subscribe to, not a method that you can call. It should be used like this:

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
}


来源:https://stackoverflow.com/questions/3880836/right-way-to-close-wpf-gui-application-getcurrentprocess-kill-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!