Home > Software engineering >  Read standard output without leaking memory
Read standard output without leaking memory

Time:01-05

How to read standard output without leaking memory? The p.StandardOutput.ReadToEnd(); is a wrong choice on large output because it allocates a large number of chars in SOH.

// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
**string output = p.StandardOutput.ReadToEnd();**
p.WaitForExit();

CodePudding user response:

Process.StandardOutput is a StreamReader, and you can read the content line by line to save memory:

// Keep looping lines while stream has not ended
while (!p.StandardOutput.EndOfStream)
{
    // Read a single line
    var line = p.StandardOutput.ReadLine();

    // ... Do something with the line
}

CodePudding user response:

You can capture output by using process.OutputDataReceived event handler and let the process notify your application of output to be received. It even works for the processes that prompt the user to input:

    Process process = new Process();
    process.StartInfo.FileName = "ipconfig.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.OutputDataReceived  = new DataReceivedEventHandler((sender, e) =>
    {
        // Prepend line numbers to each line of the output.
        if (!String.IsNullOrEmpty(e.Data))
        {
            lineCount  ;
            output.Append("\n["   lineCount   "]: "   e.Data);
        }
    });

    process.Start();

    // Asynchronously read the standard output of the spawned process.
    // This raises OutputDataReceived events for each line of output.
    process.BeginOutputReadLine();
    process.WaitForExit();

    // Write the redirected output to this application's window.
    Console.WriteLine(output);

    process.WaitForExit();
    process.Close();

    Console.WriteLine("\n\nPress any key to exit.");
    Console.ReadLine();

For more info see here

  • Related