运行Git diff会卡住,直到作为System.Diagnostics.Process
运行时被杀死。
代码:
class Program
{
static void Main(string[] args)
{
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = "git.exe";
pInfo.Arguments = "diff --name-only --exit-code V2.4-Beta-01 HEAD";
pInfo.WorkingDirectory = @"C:\Git";
pInfo.UseShellExecute = false;
pInfo.CreateNoWindow = true;
pInfo.RedirectStandardError = true;
pInfo.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = pInfo;
p.Start();
p.WaitForExit(10000);
if (!p.HasExited)
{
p.Kill();
Console.WriteLine("Killed!!!");
}
Console.WriteLine(p.StandardOutput.ReadToEnd());
Console.WriteLine(p.StandardError.ReadToEnd());
Console.ReadLine();
}
}
如何避免这种情况并使程序正常存在而不会使其超时失效?
答案 0 :(得分:1)
问题是有人必须使用stdout缓冲区,否则它将被填充并且进程被卡住(参见解释here)。差异我正在尝试检索983行,这导致缓冲区溢出。
以下是我的问题的解决方案:
class Program
{
static void Main(string[] args)
{
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = "git.exe";
pInfo.Arguments = "diff --name-only --exit-code V2.4-Beta-01 HEAD";
pInfo.WorkingDirectory = @"C:\Git";
pInfo.UseShellExecute = false;
pInfo.CreateNoWindow = true;
pInfo.RedirectStandardError = true;
pInfo.RedirectStandardOutput = true;
string output = string.Empty;
Process p = new Process();
p.StartInfo = pInfo;
p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
output += e.Data + Environment.NewLine;
}
});
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
p.Close();
Console.WriteLine(output);
Console.ReadLine();
}
}