问题
For processes with a lot of output or error, trying to redirect standard output and error with a simple
string output = process.StandardOutput.ReadToEnd();
string err = process.StandardError.ReadToEnd();
process.WaitForExit();
will cause the program to hang, and never actually finish.
回答1:
As it turns out, the large quantities of output fill up the buffers for the ReadToEnd(), causing them to never finish. One solution that seemed to work reliably for me is to create an event handler to react to the output line by line without having to react to the large block of output/error at once.
//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();
来源:https://stackoverflow.com/questions/47214380/c-sharp-process-hanging-due-to-standardoutput-readtoend-and-standarderror-read