本文介绍了C#进程由于StandardOutput.ReadToEnd()和StandardError.ReadToEnd()而挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有大量输出或错误的流程,请尝试通过简单的方法重定向标准输出和错误

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.

推荐答案

事实证明,大量输出填充了ReadToEnd()的缓冲区,导致它们永远无法完成.对于我来说似乎可靠地工作的一种解决方案是创建一个事件处理程序,以逐行对输出作出反应,而不必立即对较大的输出/错误块做出反应.

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();

这篇关于C#进程由于StandardOutput.ReadToEnd()和StandardError.ReadToEnd()而挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 13:44