×
您的位置: 首页 > 编程笔记

什么是Environment.Exit()和Application.Shutdown()之间的区别是什么?(what's difference between Environment.

WinForm Windows 时间:2020-06-18  查看:892   收藏

Sometimes application can't exit when I called Application.Shutdown, the UI was closed, but the process is still running. how to shutdown application with close all threads? does the Environment.Exit() could close all thread? or we should call Win32 API TerminateThread to do it?

解决方案

Environment.Exit() is a more brutal way of closing down your application yes, but in general if you need your kill your application to make it close then i think you looking at the problem in the wrong way. You should rather look into why are not the other threads closing gracefully ?

You could look into the FormClosing event on the main form and close down any resources thats hanging up the application preventing it from closing.

This is how i have found resources hanging up the app.

  1. In debug mode enable showing of threads ( This will allow you to see all the threads you application is running)

  2. Close the application in the way that it does not close correctly.

  3. Press pause in in Visual studio

  4. Look at the threads list, and click on them to see where int he code they are hanging, now that you can see what resources are blocking your application from closing go to your  FormClosing event and close/Dispose them there.

  5. Repeat untill the app closes correctly :)

Be aware that the threads list in debug mode will show some threads that are run but not under your control, these threads rarly have a name and when you click on them you get a message saying you have no symbols. These can be safly ignored

One of the reasons for making sure your application is closing gracefully is that if some resources ( Lets say a FileStream ) is not done working, so using some api to force it to quick can make all sorts of "random" problems come in, like settings/data files not being written and so on.

有时候,应用程序不能退出时,我称之为 Application.Shutdown 中,用户界面被关闭,但进程仍在运行。如何通过关闭所有线程关闭应用程序?确实在 Environment.Exit()可以关闭所有的线程?或者我们应该调用Win32 API TerminateThread 办呢?

解决方案

Environment.Exit ()是逼抢您的应用程序是一个更残酷的方式,但一般来说,如果你需要你杀了你的应用程序,使之接近的话,我想你看在错误的道路的问题。 你还是看看为什么没有正常关闭其他线程?

您可以看看到FormClosing在主窗体上的事件并关闭任何资源,这就是挂了应用程序$ P $从收盘pventing它。

这是我如何发现资源挂了应用程序。

  1. 在调试模式下能够呈现出threads (这将让你看到你的应用程序正在运行的线程)

  2. 关闭应用程序的方式,它不能正常关闭。

  3. preSS暂停在Visual Studio

  4. 看线程列表,点击它们,看看那里的诠释,他code,他们都挂了,现在你可以看到什么样的资源是阻止从关闭您的应用程序到您的FormClosing事件,并关闭/处置他们那里

  5. 重复,直到应用程序正确关闭:)

请注意,主题列表在调试模式会显示正在运行,但不是你的控制之下,一些线程,这些线程乙稀有一个名字,当你点击它们,你得到一个消息,说你没有符号。这些都可以safly忽略

其原因之一为确保您的应用程序正常关闭的是,如果某些资源(比方说一个的的FileStream )没有完成的工作,所以使用一些API,用它强制很快就能做出种种乱的问题来了,像设置/数据文件不会被写入等。

 

0% (0)
0% (0)