Created
September 29, 2016 14:26
-
-
Save rolfbjarne/ce764e541799c9f0ac8392418a2175be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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