我编写了一个C#应用程序,它使用System.Diagnostics.Processclass来创建一个进程
Process P1 = new Process();
P1.FileName = "myexe.exe";
Run Code Online (Sandbox Code Playgroud)
和其他适当的设置.
我把它链接到运行大约10分钟的exe文件.(我正在编写程序来测量程序的运行时间).现在介于两者之间我想中止正在运行的进程.所以我在取消按钮的事件中写道,
Process.Close();
Run Code Online (Sandbox Code Playgroud)
但是在任务管理器中我仍然看到myexe.exe正在运行,它不会被中止.该怎么办?
我Process.Kill()用来杀死一个进程.像这样:
if( !process.WaitForExit( 5000 ) ) {
process.Kill();
}
Run Code Online (Sandbox Code Playgroud)
有时进程将在行之间退出,因此控件将进入内部if然后Kill将产生异常:
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
Run Code Online (Sandbox Code Playgroud)
现在将代码包装到try-catch中似乎不是一个好主意,因为InvalidOperationException可以出于其他原因调用它.
有没有办法在所描述的场景中杀死进程而不会出现异常?