[英]How to know if a System.Diagnostic.Process has exited due to timeout?
现在我有类似
void MyMethod
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.Start();
process.WaitForExit(10); // here we set a timeout of 10 seconds
//now here I'd like to check whether the process exited normally or
//due to timeout. How do I do this?
// Important: I wanna know whether it timed out or not, not if it has exited or not.
}
我如何知道该进程是否在超时之前退出?
您可以使用Process.HasExited属性 。
获取一个值,该值指示关联的进程是否已终止。
备注
HasExited的值为true表示关联的进程已正常或异常终止。 您可以通过调用CloseMainWindow或Kill来请求或强制关联的进程退出。 如果进程打开了句柄,则操作系统将在进程退出时释放进程内存,但会保留有关进程的管理信息,例如句柄,退出代码和退出时间。 要获取此信息,可以使用ExitCode和ExitTime属性。 对于由该组件启动的进程,将自动填充这些属性。 当与系统进程相关联的所有Process组件都被销毁并且不再保存已存在进程的句柄时,将释放管理信息。
进程可以独立于您的代码而终止。 如果使用此组件启动了流程,则即使关联的流程独立退出,系统也会自动更新HasExited的值。
WaitForExit的timeout参数仅表示您的代码等待进程退出的时间。 但是,它不会终止进程本身。
此方法(WaitForExit)指示Process组件等待有限的时间以使进程退出。 如果由于终止请求被拒绝而在间隔结束之前关联的进程没有退出,则将错误返回给调用过程。”来源: http : //msdn.microsoft.com/zh-cn/library/ty0d8k56。 aspx
void MyMethod
{
using (var process = new Process())
{
process.StartInfo.FileName = "cmd.exe";
process.Start();
process.WaitForExit(10); // here we set a timeout of 10 seconds
//now here I'd like to check whether the process exited normally or
//due to timeout.
if (!process.HasExited)
{
// Do something.
}
}
}
还将过程包装在using块中,因为它实现了IDisposable
。
process.WaitForExit(10);
如果关联的进程已退出,则返回true; 否则为假。 换句话说,如果关联的进程在间隔结束之前没有退出,则将false返回给调用过程。
如https://msdn.microsoft.com/ru-ru/library/ty0d8k56(v=vs.110).aspx中所述
检查process.WaitForExit
上的布尔结果,看看是否只是由于超时而退出了。 如果要查看是否有错误,可以检查Process.ExitCode 。
我想知道是否超时与否,如果它已退出与否。
如果process.WaitForExit
返回true,则进程自行退出。 如果假进程仍在运行和超时已过期,这(在等待和恢复执行) 不杀的过程。
难道我必须手动杀死它,还是做一个使用会杀死它做了IDisposable?
你应该叫杀 。 你也应该在包装过程中using
块这样的资源配置。
void MyMethod
{
using(Process process = new Process()) {
process.StartInfo.FileName = "cmd.exe";
process.Start();
if(!process.WaitForExit(10000)) // here we set a timeout of 10 seconds (time is in milliseconds)
process.Kill(); // if you really want to stop the process, its still running here.
}
}
Process.WaitForExit
的返回值将告诉您该进程是否在超时之前退出:
void MyMethod
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.Start();
var processExited = process.WaitForExit(10); // here we set a timeout of 10 seconds
//now here I'd like to check whether the process exited normally or
//due to timeout. How do I do this?
// Important: I wanna know whether it timed out or not, not if it has exited or not.
if (processExited)
{
}
}
只需跟踪处理前后的时间即可process.WaitForExit(10);
并将其与您的超时时间进行比较(此处为10秒)。 这样,您可以知道运行该过程的确切时间,而其他方法是无法实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.