关闭 WPF GUI 应用程序的正确方法:GetCurrentProcess().Kill()、Environment.Exit(0) 或 this.Shutdown()
我的基于 GUI 桌面的 WPF 4.0 (C# .Net 4.0) 程序与 SQL Server 数据库配合使用。每次运行应用程序时,它都会通过 ADO.NET 实体框架创建与 SQL Server 的连接,如果无法访问 SQL Server,它会引发异常并显示 MessageBox
和通知。
现在我希望用户阅读此消息后应用程序将关闭。我找到了三种方法来执行此操作:
Process.GetCurrentProcess().Kill();
或
this.Shutdown(); // Application.Current.Shutdown()
或
System.Environment.Exit(0);
所有方法都工作正常并执行我需要的操作 - 关闭应用程序并在 Windows 任务管理器中终止应用程序的进程。
我的问题:
它们之间有什么区别?
哪种方式可以更快地关闭我的应用程序?
我应该使用哪种方式关闭应用程序?
Application.Current.Shutdown()
和this.Shutdown()
关闭应用程序的方式是否相同?或者也许还有另一种更合适的方法来关闭 WPF GUI 应用程序?
Application.Exit()
对我不起作用,因为我收到错误:
事件“
System.Windows.Application.Exit
”只能出现在 += 或 -= 的左侧
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.
My questions:
What is the difference between them?
Which way will close my application faster?
Which way to close application should I use?
Is
Application.Current.Shutdown()
andthis.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 -=
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Application.Current.Shutdown()
是关闭应用程序的正确方法。一般来说,因为它会触发退出事件,所以您可以处理当您想尽快终止应用程序时,应使用 Process.GetCurrentProcess().Kill() ,进一步信息。
这些方法的性质完全不同:
Shutdown()
可以暂停以结束某些操作Kill()
强制应用程序立即关闭,尽快 可能,< code>Kill() 将是最快的方法,但这有点像内核恐慌。
Application.Current.Shutdown()
is the proper way to shutdown an application. Generally, because it fires the exit events, that you can handle, further info.Process.GetCurrentProcess().Kill()
should be used when you want to kill the application as soon as possible, further info.The nature of those methods is totally different:
Shutdown()
can be paused to end some operationsKill()
forces the application to close immediately, as soon as possibleProbably,
Kill()
will be the fastest way, but this is something like kernel panic.@Damian Leszczyński - Vash 的回答几乎涵盖了您提出的 4 个具体问题。对于您关于
Application.Exit()
的最后一个问题,这是您可以订阅的事件,而不是您可以调用的方法。它应该像这样使用:@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: