3

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Can I ask why you need to call `Process.Kill`? I assume your only calling it because the program has caused some sort of error – Sayse Aug 15 '13 at 07:57
  • @Sayse: I want to be sure the process is terminated within a required timeframe. – sharptooth Aug 15 '13 at 08:07
  • Are you or the user initiating closing the application? Could you keep track if it is a programmatically initiated kill/close? – default Aug 15 '13 at 08:08
  • @Default: I don't care if it initiated X/Y - I need the process terminated no matter what. Terminated - that's it. – sharptooth Aug 15 '13 at 08:15
  • From what I've read, it looks like your try catch is your best bet (you obviously can use the NativeErrorCode here), there is also the ExitCode but this will just be -1 so probably of no help – Sayse Aug 15 '13 at 08:24

2 Answers2

1

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

Community
  • 1
  • 1
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
0

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

Or, use PInvoke to call TerminateProcess.

usr
  • 168,620
  • 35
  • 240
  • 369