Sometimes application can't exit when I called , the UI was closed, but the process is still running.时应用程序无法退出,UI 已关闭,但进程仍在运行。 how to shutdown application with close all threads? does the could close all thread? 是否可以关闭所有线程? or we should call Win32 API to do it?来做到这一点?
Environment.Exit() is a more brutal way of closing down your application, yes. But in general, if you need to kill your application to make it close then I think you're looking at the problem in the wrong way. You should rather look into why the other threads aren't closing gracefully.
You could look into the FormClosing event on the main form and close down any resources that are hanging up the application, preventing it from closing.
This is how I have found resources hanging up the app.
Be aware that the threads list in debug mode will show some threads that are run but not under your control. These threads rarely have a name and when you click on them you get a message saying you have no symbols. These can be safely ignored.
One of the reasons for making sure your application is closing gracefully is that some resources (let's say a FileStream ) are not done working, so using some API to force it to quit can make all sorts of "random" problems come in, like settings/data files not being written and so on.
As Shay said, NEVER call TerminateThread, TerminateThread kills just one thread without letting it clean up after itself this can lead to deadlocks and corruptions in other threads in the process.
TerminateProcess on the other had will kill the entire process and let the OS clean up, it's the fastest way to close a process - you just have to make sure you are not holding any resources the OS can't clean up (it also helps to close windows before calling TerminateProcess).
I think, but I haven't checked, that Environemnt.Exit calls TerminateProcess.
Application.Shutdown is very different, it doesn't immediately kill the process - it sends all the closing and shutdown notifications and waits for all the application's windows and threads close themselves.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.