Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne rolfbjarne/test.cs
Created Sep 29, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.