-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProcessExtensions.cs
69 lines (63 loc) · 2.04 KB
/
ProcessExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Turkey
{
public static class ProcessRunner
{
public static async Task<int> RunAsync(ProcessStartInfo psi, Action<string> logger, CancellationToken token)
{
logger($"Executing {psi.FileName} with arguments {psi.Arguments} in working directory {psi.WorkingDirectory}");
using var process = Process.Start(psi);
await process.WaitForExitAsync(logger, token).ConfigureAwait(false);
return process.ExitCode;
}
}
public static class ProcessExtensions
{
public static async Task WaitForExitAsync(this Process process, Action<string> logger, CancellationToken token)
{
process.EnableRaisingEvents = true;
bool captureOutput = true;
DataReceivedEventHandler logToLogger = (sender, e) =>
{
if (e.Data != null)
{
lock (logger)
{
if (captureOutput)
{
logger(e.Data);
}
}
}
};
process.OutputDataReceived += logToLogger;
process.BeginOutputReadLine();
process.ErrorDataReceived += logToLogger;
process.BeginErrorReadLine();
try
{
await process.WaitForExitAsync(token).ConfigureAwait(false);
logger($"Process Exit Code: {process.ExitCode}");
}
catch (OperationCanceledException)
{
lock (logger)
{
captureOutput = false;
}
logger($"Process wait for exit cancelled.");
try
{
process.Kill(entireProcessTree: true);
}
catch
{ }
throw;
}
}
}
}