Winforms:Application.Exit 与 Environment.Exit 与 Form.Close [英] Winforms: Application.Exit vs Environment.Exit vs Form.Close

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

问题描述

以下是我们可以退出应用程序的方式:

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

这三种方法有什么区别,什么时候用?

解决方案

正确的方法应该是 Application.Exit().根据 文档,它终止所有消息循环并关闭所有窗口,从而使您的表单可以执行其清理代码(在 Form.OnClose 等中).

Environment.Exit 只会终止进程.如果某种形式有例如未保存的更改它不会有任何机会询问用户是否要保存它们.此外,资源(数据库连接等)无法正常释放,文件可能无法刷新等.

Form.Close 就像它所说的那样:它关闭一个表单.如果您打开了其他表单(可能不是现在,而是在您的应用程序的某个未来版本中),该应用程序将不会终止.

请记住,如果您使用多线程,Application.Exit() 不会终止您的线程(因此应用程序将继续在后台工作,即使 GUI 终止).因此,您必须采取措施终止线程,无论是在主函数(即 Program.Main())中还是在主窗体的 OnClose 事件中.>

Following are the ways by which we can exit an application:

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

What is the difference between these three methods and when to use each one?

解决方案

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 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 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.

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 与 Environment.Exit 与 Form.Close的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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