How do I deal with cases when Process.Kill() yields "access denied" because the process is terminating?

4.5k views Asked by At

In my code I need to call Process.Kill() that is declared in MSDN to throw Win32Exception when either of the following occurs

  1. The associated process could not be terminated.
  2. The process is terminating.
  3. The associated process is a Win16 executable.

and sometimes I indeed face Win32Exception with Access is denied message and NativeErrorCode set to 5. MSDN says this combination happens when Kill() is called while the process is terminating. The other two cases are not documented in such details.

So I need to reasonably handle this situation. Of course I can just catch Win32Exception but how do I know why exactly it was thrown? I need to do nothing if the process is already terminating and perhaps rethrow the exception in all other cases.

How do I identify and handle this specific case?

2

There are 2 answers

0
usr On

Use try-catch. This is a design-error in the .NET framework if you ask me.

Or, use PInvoke to call TerminateProcess.

0
Bassam Alugili On

Use the command line C# to kill the task, for example Taskkill /F /IM ExeName.exe. If you do not have a persmission to kill the task than also force kill will not help.

More info Please check http://www.c-sharpcorner.com/UploadFile/8ea152/kill-process-from-the-command-prompt-in-windows-8/

here an example how to run command line in C# Run Command Prompt Commands

Greetings