C#由于StandardOutput.ReadToEnd()和StandardError.ReadToEnd()导致进程挂起
对于具有大量输出或错误的进程,尝试使用简单的C#由于StandardOutput.ReadToEnd()和StandardError.ReadToEnd()导致进程挂起,c#,process,freeze,redirectstandardoutput,C#,Process,Freeze,Redirectstandardoutput,对于具有大量输出或错误的进程,尝试使用简单的 string output = process.StandardOutput.ReadToEnd(); string err = process.StandardError.ReadToEnd(); process.WaitForExit(); 将导致程序挂起,并且永远不会真正完成 结果是,大量的输出填满了ReadToEnd()的缓冲区,导致它们永远无法完成。对我来说,一个似乎可靠的解决方案是创建一个事件处理程序,逐行对输出作出反应,而不必立即对大
string output = process.StandardOutput.ReadToEnd();
string err = process.StandardError.ReadToEnd();
process.WaitForExit();
将导致程序挂起,并且永远不会真正完成 结果是,大量的输出填满了ReadToEnd()的缓冲区,导致它们永远无法完成。对我来说,一个似乎可靠的解决方案是创建一个事件处理程序,逐行对输出作出反应,而不必立即对大量输出/错误作出反应
//create event handler
process.OutputDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
//do something with the output data 'e.Data'
log.Info("O: "+e.Data);
}
);
process.ErrorDataReceived += new DataReceivedEventHandler(
(s, e) =>
{
//do something with the error data 'e.Data'
log.Info("E: "+e.Data);
}
);
//start process
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();