我有一个调用控制台应用程序的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发布于 2018-12-21 17:59:09
process.StandardOutput.ReadToEnd();这个调用是一个阻塞调用,它将永远等待,直到被调用的进程中的所有输出都被刷新。
这意味着不需要您的process.WaitForExit调用。您真正需要做的是以异步方式读取输出流,这样您就可以选择等待输出完成的时间。
您还需要注意其他流,如StandardError,它们也可能包含输出。
这篇关于堆栈溢出的文章有some good examples of both these cases
https://stackoverflow.com/questions/53881805
复制相似问题