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

问题描述

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

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


  1. Environment.Exit(0)

  2. Application.Exit()

  3. Form.Close()

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

这三种方法之间的区别以及何时使用每种方法

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

推荐答案

正确的方法是 Application.Exit() 。根据,它将终止所有消息循环并关闭所有窗口,从而使您的表单可以执行其清理代码(在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与Environment.Exit与Form.Close的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:21