Skip to content

Instantly share code, notes, and snippets.

@micahasmith
Created March 4, 2013 19:51
Show Gist options
  • Save micahasmith/5084997 to your computer and use it in GitHub Desktop.
Save micahasmith/5084997 to your computer and use it in GitHub Desktop.
.NET Process via Async/Await
public class Runner
{
public async Task<RunResults> Run(ProcessStartInfo info)
{
var process = new Process();
var runResults = new RunResults();
//some defaults that HAVE to be in place
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.CreateNoWindow = true;
info.UseShellExecute = false;
process.StartInfo= info;
process.EnableRaisingEvents = true;
//attach to stdout
DataReceivedEventHandler onTextIn = null;
onTextIn = (o, a) =>
{
runResults.StdOut.Append(a.Data);
};
process.OutputDataReceived += onTextIn;
//attach to error
DataReceivedEventHandler onError = null;
onError = (o, a) =>
{
runResults.StdOut.Append(a.Data);
};
process.ErrorDataReceived += onError;
//put detachment in one place
Action dispose = () =>
{
process.ErrorDataReceived -= onError;
process.OutputDataReceived -= onTextIn;
};
//attach to exit
EventHandler onExit = null;
TaskCompletionSource<bool> tcsExit = new TaskCompletionSource<bool>();
onExit = (o,a)=>
{
process.Exited-=onExit;
process.Dispose();
tcsExit.TrySetResult(true);
};
process.Exited += onExit;
//attach to disposed
EventHandler onDispose = null;
TaskCompletionSource<bool> tcsDispose = new TaskCompletionSource<bool>();
onDispose = (o,a)=>
{
process.Disposed-=onDispose;
dispose();
tcsDispose.TrySetResult(false);
};
process.Disposed += onDispose;
//kick off the process
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
//wait for any of these to finish
var tasks = new Task<bool>[]
{
tcsExit.Task,
tcsDispose.Task
};
var finisher = await Task.WhenAny(tasks);
runResults.HadError = finisher.Result;
return runResults;
}
}
public class RunResults
{
public bool HadError{get;set;}
public string ResultUri{get;set;}
public StringBuilder StdOut { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment