How to kill a process without getting a “process has exited” exception?

后端 未结 2 1744
礼貌的吻别
礼貌的吻别 2020-12-04 01:45

I use Process.Kill() to kill a process. Like this:

if( !process.WaitForExit( 5000 ) ) {
   process.Kill();
}

and sometimes the

相关标签:
2条回答
  • 2020-12-04 02:08

    You could P/Invoke TerminateProcess passing it Process.Handle. Then manually evaluating the cause of it (GetLastError()). Which is roughly, what Process.Kill() does internally.

    But note that TerminateProcess is asynchronous. So you'd have to wait on the process handle to be sure it is done. Using Process.Kill() does that for your.

    Update: Correction, Process.Kill() also runs asynchronously. So you'll have to use WaitForExit() to wait for termination to complete - if you care.

    Frankly, I wouldn't bother. Of course there is always the (remote?) chance that some "arbitrary" InvalidOperationExcepion bubbles up out of that line of code, that is not related to the process no longer being there or the Process object to be in an invalid state, but in reality I think you can just go with the try/catch around the Kill.

    In addition, depending on your application, you could consider logging this kill anyway, since it seems some sort of last resort measure. In that case log the actual InvalidOperationException with it. If things go strange, you at least have your logs to check why the Kill failed.

    Having all that said, you might also want to consider catching / handling Win32Exception for the same reasons.

    0 讨论(0)
  • 2020-12-04 02:09

    You need to use HasExited:

    if(!process.WaitForExit(5000)) 
    {
       if (!process.HasExited)
       {
           process.Kill();
       }
    }
    

    See here:

    http://msdn.microsoft.com/en-us/library/system.diagnostics.process.hasexited.aspx

    0 讨论(0)
提交回复
热议问题