用System.Diagnostics.Process的ReadEnd卡死
2025/06
07
11:06
例如执行git pull会卡死
用BeginOutputReadLine+OutputDataReceived 就不会卡死
private static string Execute(string workDir, string cmd, string args, ref string errInfo)
{
Console.WriteLine($"{cmd} {args}");
StringBuilder errstr = new StringBuilder();
StringBuilder outstr = new StringBuilder();
var myProcess = new System.Diagnostics.Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = cmd;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.Arguments = args;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
myProcess.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
myProcess.Start();
myProcess.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
{
Console.WriteLine(e.Data);
errstr.AppendLine(e.Data);
};
myProcess.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
outstr.AppendLine(e.Data);
};
myProcess.BeginErrorReadLine();
myProcess.BeginOutputReadLine();
myProcess.WaitForExit();
myProcess.Close();
}
catch (System.Exception e)
{
outstr.AppendLine(e.ToString());
}
errInfo = errstr.ToString();
return outstr.ToString();
}
}
CopyRights: The Post by BY-NC-SA For Authorization,Original If Not Noted,Reprint Please Indicate From 老刘@开发笔记
Post Link: 用System.Diagnostics.Process的ReadEnd卡死
Post Link: 用System.Diagnostics.Process的ReadEnd卡死