我有一个 Windows 服务调用控制台应用程序并读取控制台输出以确定状态。
在调用 StandardOutput.ReadToEnd() 后,我在有时间限制的情况下调用 WaitForExit()。
问题是如果控制台应用程序花费的时间超过 WaitForExit() 的时间限制,那么 ReadToEnd() 会阻塞直到可执行文件退出,从而使 WaitForExit() 变得多余?
Process process = new Process();
process.StartInfo = new ProcessStartInfo
{
FileName = pathToExecutable,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
process.Start();
// Adding ReadToEnd() before the WaitForExit() call to prevent deadlocks in case Process buffer size becomes full
// Ref: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput?redirectedfrom=MSDN&view=netframework-4.5.2#remarks
response = process.StandardOutput.ReadToEnd();
process.WaitForExit(waitForExitInSeconds * 1000);
process.Close();
// Read response string and determine status