Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I use Process.GetCurrentProcess().Kill() to exit my WinForm application?

Tags:

Right now, when the user want to exit my application, I do the few things I have to (ie disconnecting from the server, saving the user data...) and then I do the following :

  • Exit all my mainloops using booleans
  • abort the threads still running (typically, my server polling thread)
  • kindly call Application.Exit();

This takes a few seconds to exit, and serves no real purpose (everything is already saved on the server, so I don't really care what happens there)

If I use this instead, I got instant termination with no drawback I can think of :

 System.Diagnostics.Process.GetCurrentProcess().Kill(); 

Why wouldn't I just terminate my process and let the CLR drop the AppDomain ?

I know that carefully disposing your shared resources (IO file handlers, etc.) is important (so please don't answer that:)), but once it's done, is there a real reason to cleanly exit my App ?

like image 605
Brann Avatar asked Mar 04 '09 09:03

Brann


People also ask

What does process kill do?

The Kill method forces a termination of the process, while CloseMainWindow only requests a termination. When a process with a graphical interface is executing, its message loop is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system.

How do you exit a process in C#?

When we need to exit or close opened form then we should use "this. Close( )" method to close the form on some button click event. When we are running a winform application & need to exit or close SUB APPLICATION or CURRENT THREAD then we should use "System.


2 Answers

Killing the process would mean that finally blocks will not be executed, and probably not even critical finalizer objects, which may actually be critical, and cause resource leakage at system level. It can also cause unexpected bugs in the future when someone else maintains the code, as they (or you) will have to twist their heads, having to think every time they write a finally block whether it will be executed.

like image 146
Hosam Aly Avatar answered Sep 24 '22 06:09

Hosam Aly


That's indeed a good question!

Once upon a time (over ten years ago) I wrote a VB6 app wich hung at termination due to a confirmed bug in the WinINet OCX (or whatever it was called) due to the particular certificate used on a web server it was talking to.

Without any way to come around this bug I used TerminateProcess and for all that I know, this app was in use on several thousand machines for several years and I never heard of any problem regarding this hack!

like image 43
Dan Byström Avatar answered Sep 24 '22 06:09

Dan Byström