终止应用程序实例的最佳方法
终止应用程序实例的最佳方法是什么? 我知道这三种方法:
Application.Exit()
Environment.Exit(0 )
Process.GetCurrentProcess().Kill()
谁能告诉我哪个更好或者什么时候使用上面的每一个是合适的?
What is the best way to kill an application instance?
I am aware of these three methods:
Application.Exit()
Environment.Exit(0)
Process.GetCurrentProcess().Kill()
Can anyone tell me which is better or when using each of the above would be appropriate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 c# 常见问题解答的指南:
System.Windows.Forms.Application.Exit() - 通知所有消息泵必须终止,然后在处理消息后关闭所有应用程序窗口。此方法停止所有线程上正在运行的所有消息循环并关闭应用程序的所有窗口。此方法不会强制应用程序退出。 Exit 方法通常从消息循环内调用,并强制 Run 返回。要仅退出当前线程的消息循环,请调用 ExitThread。如果您正在运行 WinForms 应用程序,则需要使用此调用。作为一般准则,如果您已调用 System.Windows.Forms.Application.Run,请使用此调用。
System.Environment.Exit(exitCode) - 终止此进程并向底层操作系统提供指定的退出代码。此调用要求您具有 SecurityPermissionFlag.UnmanagedCode 权限。如果不这样做,则会发生 SecurityException 错误。如果您正在运行控制台应用程序,则需要使用此调用。
可能不建议终止该进程。
guidelines from c# faq:
System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread. This is the call to use if you are running a WinForms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run.
System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.
Killing the process is likely not recommended.
如果这是 Windows 窗体应用程序,请使用 Application.Exit()。这将很好地关闭程序。
If this is a Windows Forms application, use Application.Exit(). That will close the program nicely.
只是一个快速回答,当它起作用时我总是会使用“退出”选项。这是一种更干净的方法。
“杀死”进程正是这个意思,因此程序无法执行它可能想做的任何清理工作(例如保存配置、保存其他文件等)。除非您知道该过程是什么并且它没有任何“清理”要做,即使这样,使用“退出”也更干净。
您提到的两个“退出”选项之间似乎没有任何区别,我敢打赌第一个选项只是隐式传递零值。
Just a quick answer, I would always use the "Exit" option when it will work. It is a much cleaner way to do it.
To "Kill" a process means exactly that, and therefore the program does not get to do any cleanup work it might want to do (like saving configuration, saving other files, etc...). Unless you know what the process is and that it does not have any "cleanup" to do, and even then, it's just cleaner to use "Exit."
There does not appear to be any difference between the two "Exit" options you mention, I would wager that the first is simply implicitly passing the zero value.