Skip to content

Commit

Permalink
Read stderr asynchronously to prevent hang if many errors logged (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
peitschie authored Nov 15, 2023
1 parent ba62afe commit ed40b89
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions Rubjerg.Graphviz/GraphvizCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;

namespace Rubjerg.Graphviz;

Expand Down Expand Up @@ -64,7 +65,11 @@ public static (byte[] stdout, string stderr) Exec(Graph input, string format = "
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardError = true;

StringBuilder stderr = new StringBuilder();
process.ErrorDataReceived += (_, e) => stderr.AppendLine(e.Data);

_ = process.Start();
process.BeginErrorReadLine();

// Write to stdin
using (StreamWriter sw = process.StandardInput)
Expand All @@ -78,12 +83,6 @@ public static (byte[] stdout, string stderr) Exec(Graph input, string format = "
stdout = memoryStream.ToArray();
}

// Read from stderr
string stderr;
using (StreamReader sr = process.StandardError)
// Let's use unix line endings for consistency with stdout
stderr = sr.ReadToEnd().Replace("\r\n", "\n");

process.WaitForExit();

if (process.ExitCode != 0)
Expand All @@ -94,7 +93,8 @@ public static (byte[] stdout, string stderr) Exec(Graph input, string format = "
else
{
// Process completed successfully.
return (stdout, stderr);
// Let's use unix line endings for consistency with stdout
return (stdout, stderr.ToString().Replace("\r\n", "\n"));
}
}
}

0 comments on commit ed40b89

Please sign in to comment.