我一直在观察,即使进程仍在运行,Process.HasExited
有时也会返回true
.
我的代码在下面启动一个名为"testprogram.exe"的进程,然后等待它退出.问题是有时我会抛出异常; 似乎即使HasExited
返回true
过程本身在系统中仍然存在 - 这怎么可能?
我的程序在它终止之前写入日志文件,因此我需要在读取之前绝对确定该日志文件存在(也就是进程已终止/完成).不断检查它的存在不是一种选择.
// Create new process object
process = new Process();
// Setup event handlers
process.EnableRaisingEvents = true;
process.OutputDataReceived += OutputDataReceivedEvent;
process.ErrorDataReceived += ErrorDataReceivedEvent;
process.Exited += ProgramExitedEvent;
// Setup start info
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = ExePath,
// Must be false to redirect IO
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = arguments
};
process.StartInfo = psi;
// Start the program
process.Start(); …
Run Code Online (Sandbox Code Playgroud)