You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取标准输出且避免内存泄漏?

如何读取进程标准输出并避免内存泄漏?

在处理大输出场景时,p.StandardOutput.ReadToEnd();并不是正确的选择——它会在内存中一次性分配大量字符,容易引发内存占用过高甚至泄漏的问题。

推荐的处理方式:逐行或流式读取

我们可以通过逐行读取输出流或分块流式处理的方式,避免一次性加载全部内容到内存中,示例代码如下:

逐行读取示例

// 启动子进程
Process p = new Process();
// 重定向子进程的输出流
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();

// 逐行读取输出,实时处理每一行内容
while (!p.StandardOutput.EndOfStream)
{
    string line = p.StandardOutput.ReadLine();
    // 在这里添加对单行内容的处理逻辑,比如写入文件、业务分析等
    // ProcessSingleLine(line);
}

p.WaitForExit();

分块流式处理示例

如果需要更灵活的字节级控制,可以直接操作底层流对象,自定义缓冲区大小:

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();

// 使用using语句确保流资源自动释放
using (StreamReader reader = p.StandardOutput)
using (FileStream outputFile = new FileStream("process_output.txt", FileMode.Create))
using (StreamWriter fileWriter = new StreamWriter(outputFile))
{
    char[] buffer = new char[4096]; // 根据实际场景调整缓冲区大小
    int readCount;
    while ((readCount = reader.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileWriter.Write(buffer, 0, readCount);
        // 也可以直接对缓冲区内容做实时处理
    }
}

p.WaitForExit();

关键注意事项

  • 坚决避免一次性读取全部输出内容到内存,改用逐行或分块的增量处理方式
  • 利用using语句管理流对象,确保资源被正确释放,杜绝资源泄漏
  • 读取到内容后及时处理,不要在内存中堆积大量未处理的数据

内容的提问来源于stack exchange,提问作者Tomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:35:18