【问题标题】:C# process hanging due to StandardOutput.ReadToEnd() and StandardError.ReadToEnd() [duplicate]由于 StandardOutput.ReadToEnd() 和 StandardError.ReadToEnd() 而导致 C# 进程挂起 [重复]
【发布时间】:2018-04-23 04:29:06
【问题描述】:

对于有大量输出或错误的进程,尝试用一个简单的重定向标准输出和错误

string output = process.StandardOutput.ReadToEnd();
string err = process.StandardError.ReadToEnd();
process.WaitForExit();

将导致程序挂起,并且永远不会真正完成。

【问题讨论】:

    标签: c# process freeze redirectstandardoutput


    【解决方案1】:

    事实证明,大量输出填满了 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();
    

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多