我有以下代码:
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents
我知道我开始的进程的输出大约是7MB长。在Windows控制台中运行它可以正常工作。不幸的是,在编程上,这在WaitForExit
上无限期地挂起。另请注意,对于较小的输出(如3KB),此代码不会挂起。
有没有可能ProcessStartInfo
内部的StandardOutput
不能缓冲7MB?如果是这样,我应该怎么做呢?如果不是,我做错了什么?
发布于 2018-11-28 01:06:10
我认为使用异步,可能会有一个更优雅的解决方案,即使同时使用standardOutput和standardError也不会出现死锁:
using (Process process = new Process())
{
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
var tStandardOutput = process.StandardOutput.ReadToEndAsync();
var tStandardError = process.StandardError.ReadToEndAsync();
if (process.WaitForExit(timeout))
{
string output = await tStandardOutput;
string errors = await tStandardError;
// Process completed. Check process.ExitCode here.
}
else
{
// Timed out.
}
}
它是基于Mark Byer回答。如果不使用异步方法,则可以使用string output = tStandardOutput.result;
而不是await
https://stackoverflow.com/questions/139593
复制相似问题