Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code, 'Application.Exit()' does not terminate the program. Is there anouther way to do this, to immediatly terminate the program? This code is in an object that is created presumably before the application's main form. This object does recource checking and activation checks.
Posted

The solution by digimanus works, but it needs explanation, and the article referenced is pretty bad.

The exit methods of System.Windows.Forms.Application actually have nothing to do with the termination of the process where application is running. They only cause the method Application.Run to return.

The method Application.Exit exits the application but completes message pumping, so Application.Run does not return immediately. The method Application.ExitThread returns from the loop; so it happens as soon as the current message is dispatched and execution returns to the loop.

These method affect only one thread, the UI thread. So, the process is not terminated if there is another thread which is kept executing. This is the most typical reason of execution of the process after "normal" Application.Exit. The method System.Environment.Exit works anyway. However, I would not recommend it. The threads should be correctly terminated or correctly aborted because some post-processing in the aborted thread can be important. System.Environment.Exit is a careless way. The best way of accurate exit is closing of the main form and doing all post-processing including thread termination triggered in its FormClosed event.

Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.aspx[^],
http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx[^].

—SA
 
Share this answer
 
Comments
Lakamraju Raghuram 31-Jan-12 22:44pm    
This is one great explanation. I have enjoyed it.
+5.
Sergey Alexandrovich Kryukov 31-Jan-12 22:46pm    
Thank you, Lakamraju.
--SA
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 31-Jan-12 22:41pm    
It works, but I voted 4.

1) The article you referenced is pretty bad. For more accurate information, please see my answer.

2) The method you show it pretty much brute force. It's much better to investigate why application does not exit normally and fix the root problem. I also explain it in my answer.

However, your information is valuable, just needs accurate explanation.
--SA
Try Application.ExitThread function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900