Skip to content

Instantly share code, notes, and snippets.

@pizycki
Created April 10, 2019 08:06
Show Gist options
  • Select an option

  • Save pizycki/4f3367275f2f97ca07079afb75c26c2b to your computer and use it in GitHub Desktop.

Select an option

Save pizycki/4f3367275f2f97ca07079afb75c26c2b to your computer and use it in GitHub Desktop.
Helper class for runnsing new processes
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using CSharpFunctionalExtensions;
namespace Common
{
public class ProcessRunner
{
private const int PROCESS_TIMEOUT = 1000 * 60; // ms
public Result<ImmutableList<string>, ImmutableList<string>> Run((string program, string args) command)
{
var (program, args) = command;
var psi = new ProcessStartInfo(program, args)
{
ErrorDialog = false,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = Process.Start(psi);
var stdOut = new List<string>();
var stdErr = new List<string>();
proc.OutputDataReceived += (sender, outputLine) =>
{
if (outputLine.Data != null) stdOut.Add(outputLine.Data);
};
proc.ErrorDataReceived += (sender, errorLine) =>
{
if (errorLine.Data != null) stdErr.Add(errorLine.Data);
};
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit(PROCESS_TIMEOUT);
return proc.ExitCode == ExitCodes.Success
? Result.Ok<ImmutableList<string>, ImmutableList<string>>(stdOut.ToImmutableList())
: Result.Fail<ImmutableList<string>, ImmutableList<string>>(stdErr.ToImmutableList());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment