-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessRunner.cs
111 lines (89 loc) · 2.32 KB
/
ProcessRunner.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System.Diagnostics;
namespace Brainstorm.Rig.Services;
public class ProcessRunner : IDisposable
{
public readonly Process Process;
bool disposed = false;
public bool Running { get; private set; } = false;
static ProcessStartInfo GetConfiguration(string connection) =>
new()
{
FileName = "dotnet",
Arguments = $"run --project \"..\\Brainstorm.Api\" /ConnectionStrings:App=\"{connection}\"",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
void EndProcess()
{
if (disposed)
return;
Kill();
Process.Dispose();
disposed = true;
}
DataReceivedEventHandler ProcessOutput =>
new((sender, e) =>
{
if (!Running && e.Data.Contains("Now listening on: http://localhost:5000"))
Running = true;
Console.WriteLine(e.Data);
});
DataReceivedEventHandler ProcessError =>
new((sender, e) =>
{
Running = !Process.HasExited;
Console.WriteLine(e.Data);
});
EventHandler ProcessExit =>
new((sender, e) => Running = false);
public ProcessRunner(string connection)
{
Process = new()
{
StartInfo = GetConfiguration(connection)
};
Process.OutputDataReceived += ProcessOutput;
Process.ErrorDataReceived += ProcessError;
Process.Exited += ProcessExit;
}
~ProcessRunner()
{
EndProcess();
}
public bool Start()
{
Kill();
var res = Process.Start();
Process.BeginOutputReadLine();
Process.BeginErrorReadLine();
if (res)
while (!Running) { }
return res;
}
public bool Kill()
{
try
{
if (Running)
{
Process.CancelOutputRead();
Process.CancelErrorRead();
Process.Kill();
}
Running = false;
return true;
}
catch
{
return false;
}
}
public void Dispose()
{
EndProcess();
GC.SuppressFinalize(this);
}
}