What is the difference between Environment.Exit () and Application.Shutdown ()?

Sometimes the application cannot exit when I called Application.Shutdown , the user interface was closed, but the process still works. How to close the application with closing all threads? can Environment.Exit () close all threads? or should we call the Win32 API TerminateThread to do this?

+16
c #
May 25 '09 at 6:13
source share
3 answers

Environment.Exit () is a more brutal way to close the application, but in general, if you need to kill the application to close it, I think that you are considering the problem wrong. You should better study why other threads are not closing?

You can look into the FormClosing event in the main form and close all resources that suspend the application, preventing it from closing.

This is how I found application specific resources.

  • In debug mode, turn on threads (this will allow you to see all the threads that the application is running on)
  • Close the application so that it is not properly closed.
  • Click the pause button in Visual Studio
  • Look at the list of topics and click on them to see where it is in the code that they hang, now that you can see which resources block your application from closing, go to the FormClosing event and close it / Dispose.
  • Repeat until the application closes correctly :)

Keep in mind that the list of threads in debug mode will show some threads that are started, but not under your control, these threads have a name, and when you click on them, you get a message that you have no characters. They can be safely ignored.

One of the reasons that your application closes gracefully is because if some resources (say, FileStream ) do not work, therefore, using some api to make it fast, all kinds of β€œrandom” problems, for example, files settings / data that are not recorded, etc.

+17
May 25 '09 at 6:29 a.m.
source share
  • You should NEVER call TerminateThread
  • Make sure that all the threads that you created are marked as background, so when you close the application, it will not wait for them to complete.
+8
May 25 '09 at 6:33
source share

As Shay said, NEVER call TerminateThread, TerminateThread kills only one thread, not allowing it to clear after itself, this can lead to deadlocks and distortions in other threads of the process.

TerminateProcess, on the other hand, will kill the whole process and allow the OS to clean, this is the fastest way to close the process - you just need to make sure that you are not holding any resources that the OS cannot clear (this also helps close windows before calling TerminateProcess).

I think, but I have not verified that Environemnt.Exit calls TerminateProcess.

Application.Shutdown is very different, it does not immediately kill the process - it sends all notifications of closing and shutting down and waits for all application windows and threads to close.

+1
May 25 '09 at 7:10
source share



All Articles