C# process hanging due to StandardOutput.ReadToEnd() and StandardError.ReadToEnd() [duplicate]

蹲街弑〆低调 提交于 2020-08-08 08:17:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!