Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's difference between Environment.Exit() and Application.Shutdown()?

Tags:

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?

like image 353
Cooper.Wu Avatar asked May 25 '09 06:05

Cooper.Wu


People also ask

What does environment exit do?

Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated. Exit requires the caller to have permission to call unmanaged code.

What is application Exit?

The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.

How do I exit Winforms application?

The proper method would be Application. Exit() .

What is the statement that closes the form?

this.Close() When a form is closed, all resources created within the object are closed and the form is disposed.


1 Answers

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.

  1. In debug mode, enable showing of threads. (This will allow you to see all the threads your application is running.)
  2. Close the application in the way that it does not close correctly.
  3. Press pause in Visual studio.
  4. Look at the threads list, and click on them to see where is the 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 until 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 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.

like image 117
EKS Avatar answered Oct 16 '22 04:10

EKS