关闭WPF GUI应用程序的正确方法:GetCurrentProcess()。Kill(),Environment.Exit(0)或this.Shutdown()

问题描述 投票:49回答:4

我的基于GUI桌面的WPF 4.0(C#.Net 4.0)程序适用于SQL Server数据库。每次运行我的应用程序时,它都会通过ADO.NET Entity Framework创建与SQL Server的连接,如果SQL Server无法访问,则会抛出异常并显示带有通知的MessageBox

现在我希望在用户阅读此消息后,应用程序将关闭。我找到了三种方法:

Process.GetCurrentProcess().Kill();

要么

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

要么

System.Environment.Exit(0);

所有这些都可以正常工作并做我需要的 - 在Windows任务管理器中关闭应用程序并终止应用程序进程。

我想知道:

  1. 他们之间有什么区别?
  2. 哪种方式可以更快地关闭我的申请?
  3. 我应该使用哪种方式关闭应用程序?
  4. Application.Current.Shutdown()this.Shutdown()以同样的方式关闭申请吗?

或者可能还有另一种更合适的方法来关闭WPF GUI应用程序?

当我收到错误时,Application.Exit()对我不起作用:

事件'System.Windows.Application.Exit'只能出现在+ =或 - =的左侧

谢谢。

c# wpf database exception-handling close-application
4个回答
68
投票

Application.Current.Shutdown()是关闭应用程序的正确方法。一般因为火灾退出事件,你可以处理more

当你想杀死应用程序时,应该使用Process.GetCurrentProcess().Kill()more

AD1。这些方法的性质完全不同。关闭进程可以暂停以结束某些操作,杀死应用程序关闭。

AD2。可能Kill()将是最快的方式,但这就像内核恐慌。

AD3。关闭,因为它会触发关闭事件

AD4。这取决于this是什么。


2
投票

使用Application.Current.Shutdown();

在App.xaml中添加ShutdownMode =“OnMainWindowClose”


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

1
投票

@DamianLeszczyński - Vash的答案几乎涵盖了你提出的4个具体问题。关于Application.Exit()的最后一个问题,这是您可以订阅的事件,而不是您可以调用的方法。它应该像这样使用:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.