我想确保我的逻辑在这里是正确的。我想运行一个进程timeout
几秒钟,如果它运行更长时间,它应该立即被杀死。
该completed
标志应该可靠地指示进程是否按预期完成,例如没有被杀死,没有崩溃或抛出异常。
process.HasExited
另外,如果检查正确,我也不肯定。如果process.WaitForExit()
返回 false 并Kill()
成功,那么将process.HasExited
永远为 true?那将是我的假设,但我想确认。另外,如果 Kill() 失败,除了记录之外,如果有什么可以做的呢?
using (process = new Process())
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);
process.Exited += new EventHandler(OnExited);
process.StartInfo = startInfo;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (!process.WaitForExit(timeout))
{
try
{
process.Kill();
}
catch (Exception e)
{
LogError(e, MethodBase.GetCurrentMethod());
}
finally
{
this.completed = false;
}
}
else
{
if (process.HasExited)
{
this.code = process.ExitCode;
this.completed = true;
}
else
{
this.completed = false;
}
}
}