views:

40

answers:

3

What is the best way to kill an application instance? I am aware of these three methods:

Application.Exit()

Environment.Exit(0)

Process.GetCurrentProcess().Kill()

Can anyone tell me which is better or when using each of the above would be appropriate?

A: 

Just a quick answer, I would always use the "Exit" option when it will work. It is a much cleaner way to do it.

To "Kill" a process means exactly that, and therefore the program does not get to do any cleanup work it might want to do (like saving configuration, saving other files, etc...). Unless you know what the process is and that it does not have any "cleanup" to do, and even then, it's just cleaner to use "Exit."

There does not appear to be any difference between the two "Exit" options you mention, I would wager that the first is simply implicitly passing the zero value.

gnomed
I see, thanks for the info. This is a critical security check so it would probably be better for me to kill it since I do not want the app to run it all if it fails this check.
Eaton
+4  A: 

guidelines from c# faq:

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread. This is the call to use if you are running a WinForms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run.

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

Killing the process is likely not recommended.

Orbit
Thanks, lots of good info.
Eaton
+1  A: 

If this is a Windows Forms application, use Application.Exit(). That will close the program nicely.

Reed Copsey