的WinForms:Application.Exit VS Enviroment.Exit VS Form.Close [英] Winforms: Application.Exit vs Enviroment.Exit vs Form.Close

查看:286
本文介绍了的WinForms:Application.Exit VS Enviroment.Exit VS Form.Close的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  如何正确退出C#应用程序?

我已经调查什么是我们可以退出应用程序的方式:

I have investigated what are the ways we can exit an application:

  1. Enviroment.Exit(0)
  2. Application.Exit()
  3. Form.Close()
  1. Enviroment.Exit(0)
  2. Application.Exit()
  3. Form.Close()

这是关闭应用程序,为什么最好的方式?

Which is the best way of closing an application and why?

推荐答案

正确的方法是 Application.Exit()。根据<一href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.exit%28v=vs.80%29.aspx">Documentation,它终止所有的消息循环,并关闭所有窗口从而使您的形式,以执行其清理code(在Form.OnClose等)的可能性。

The proper method would be Application.Exit(). According to the Documentation, it terminates all message loops and closes all windows thus giving your forms the possibility to execute their cleanup code (in Form.OnClose etc).

Environment.Exit 只想杀死进程。如果某种形式的有例如未保存的更改也不会有任何机会询问用户,如果他想拯救他们。同样的资源(数据库连接等)无法正常释放,文件可能不会被刷新等。

Environment.Exit would just kill the process. If some form has e.g. unsaved changes it would not have any chances to ask the user if he wants to save them. Also resources (database connections etc.) could not be released properly, files might not be flushed etc.

Form.Close 少了点什么它说:它关闭的形式。如果你有其他形式的开(也许不是现在,但在应用程序的某个未来版本),应用程序将不会终止。

Form.Close just does what it says: it closes a form. If you have other forms opened (perhaps not now but in some future version of your application), the application will not terminate.

请记住,如果你使用多线程, Application.Exit()将不会终止你的线程(因此应用程序将继续在后台运行,即使GUI被终止)。因此,你必须采取措施来杀你的线程,无论是在主函数(即 Program.Main()),或者当在的OnClose 活动的主要形式。

Keep in mind that if you use multithreading, Application.Exit() will not terminate your threads (and thus the application will keep working in the background, even if the GUI is terminated). Therefore you must take measures to kill your threads, either in the main function (i.e. Program.Main()) or when in the OnClose event of your main form.

这篇关于的WinForms:Application.Exit VS Enviroment.Exit VS Form.Close的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆