Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne
Created September 29, 2016 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolfbjarne/ce764e541799c9f0ac8392418a2175be to your computer and use it in GitHub Desktop.
Save rolfbjarne/ce764e541799c9f0ac8392418a2175be to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
class C {
static void Main ()
{
Console.WriteLine ($"PID: {Process.GetCurrentProcess ().Id}");
for (int i = 0; i < 10000; i++) {
Console.WriteLine ($"Iteration #{i}");
RunProcess ();
}
}
static void RunProcess ()
{
var info = new ProcessStartInfo ("echo", "abc");
info.UseShellExecute = false;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
var stdout_completed = new System.Threading.ManualResetEvent (false);
var stderr_completed = new System.Threading.ManualResetEvent (false);
var output = new StringBuilder ();
using (var p = Process.Start (info)) {
p.OutputDataReceived += (s, e) => {
if (e.Data != null) {
lock (output)
output.AppendLine (e.Data);
} else {
stdout_completed.Set ();
}
};
p.ErrorDataReceived += (s, e) => {
if (e.Data != null) {
lock (output)
output.AppendLine (e.Data);
} else {
stderr_completed.Set ();
}
};
p.BeginOutputReadLine ();
p.BeginErrorReadLine ();
p.WaitForExit ();
stderr_completed.WaitOne (TimeSpan.FromSeconds (1));
stdout_completed.WaitOne (TimeSpan.FromSeconds (1));
Console.Error.WriteLine ($"Process exited with code {p.ExitCode}");
Console.WriteLine (output.ToString ());
p.StandardOutput.Close ();
// FIX:
// GC.Collect ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment