由于 StandardOutput.ReadToEnd() 和 StandardError.ReadToEnd(),C# 进程挂起

标签 c# process freeze redirectstandardoutput

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

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

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

最佳答案

事实证明,大量输出填满了 ReadToEnd() 的缓冲区,导致它们永远无法完成。对我来说似乎可靠的一种解决方案是创建一个事件处理程序来逐行对输出使用react,而不必立即对大块输出/错误使用react。

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

关于由于 StandardOutput.ReadToEnd() 和 StandardError.ReadToEnd(),C# 进程挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47214380/

相关文章:

c# - 将 C# Count() 与函数一起使用

Java进程挂起并继续

c - 解析和 evecvp 问题

javascript - css to json 解析器卡住浏览器窗口

c# - 在 WPF 中创建自定义用户界面

c# - ThreadPool 挫折 - 线程创建超过 SetMaxThreads

process - 优先老化作为进程调度策略。有哪些优点和缺点?

c++ - 如何检测程序陷入无限循环的位置?

java - 当 while(true) 在线程中循环时 JFrame 卡住

c# - 如何让代码契约相信变量不为空?