问题描述
我使用 Process.Kill()
来终止一个进程.像这样:
I use Process.Kill()
to kill a process. Like this:
if( !process.WaitForExit( 5000 ) ) {
process.Kill();
}
有时进程会在两行之间退出,所以控制会进入if
然后Kill
会产生一个异常:
and sometimes the process will exit right in between the lines, so control will get inside if
and then Kill
will yield an exception:
System.InvalidOperationException
Cannot process request because the process (ProcessIdHere) has exited.
at System.Diagnostics.Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
at System.Diagnostics.Process.Kill()
//my code here
现在将代码包装到 try-catch 中似乎不是一个好主意,因为可以出于其他原因调用 InvalidOperationException
.
Now wrapping the code into try-catch doesn't seem to be a good idea because InvalidOperationException
can be called for other reasons.
在所描述的场景中,有没有办法杀死进程而不出现异常?
Is there a way to kill a process without getting an exception in the described scenario?
推荐答案
您可以 P/Invoke TerminateProcess
传递它 Process.Handle
.然后手动评估它的原因(GetLastError()
).大致上,Process.Kill()
在内部做了什么.
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.
但请注意 TerminateProcess
是异步的.所以你必须等待进程句柄以确保它完成.
But note that TerminateProcess
is asynchronous. So you'd have to wait on the process handle to be sure it is done.
更新:更正,Process.Kill()
也异步运行.所以你必须使用 WaitForExit()
来等待终止完成 - 如果你关心的话.
Update: Correction, Process.Kill()
also runs asynchronously. So you'll have to use WaitForExit()
to wait for termination to complete - if you care.
坦率地说,我不会打扰.当然,总是有(远程?)一些任意"InvalidOperationExcepion
从那行代码中冒出来的机会,这与不再存在的进程或 Process 无关
对象处于无效状态,但实际上我认为您可以在 Kill
周围使用 try/catch.
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
.
此外,根据您的应用程序,您无论如何都可以考虑记录此杀戮,因为这似乎是某种不得已的措施.在这种情况下,用它记录实际的 InvalidOperationException
.如果事情变得奇怪,你至少有你的日志来检查 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.
综上所述,出于同样的原因,您可能还想考虑捕获/处理 Win32Exception
.
Having all that said, you might also want to consider catching / handling Win32Exception
for the same reasons.
这篇关于如何在不出现“进程已退出"的情况下杀死进程例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!