-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProcessExecutor.cs
126 lines (110 loc) · 4.19 KB
/
ProcessExecutor.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CefDetector.Net
{
public class ProcessExecutor : IDisposable
{
public event EventHandler<int>? OnExited;
public event EventHandler<string>? OnOutputDataReceived;
public event EventHandler<string>? OnErrorDataReceived;
protected readonly Process _process;
protected bool _started;
public ProcessExecutor( string binPath ) : this( new ProcessStartInfo( binPath ) ) { }
public ProcessExecutor( string binPath,
string arguments ) : this( new ProcessStartInfo( binPath, arguments ) ) { }
public ProcessExecutor( ProcessStartInfo startInfo )
{
_process = new Process()
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.CreateNoWindow = true;
_process.StartInfo.RedirectStandardOutput = true;
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardError = true;
}
protected virtual void InitializeEvents()
{
_process.OutputDataReceived += ( sender,
args ) =>
{
if ( args.Data != null )
{
OnOutputDataReceived?.Invoke( sender, args.Data );
}
};
_process.ErrorDataReceived += ( sender,
args ) =>
{
if ( args.Data != null )
{
OnErrorDataReceived?.Invoke( sender, args.Data );
}
};
_process.Exited += ( sender,
args ) =>
{
if ( sender is Process process )
{
OnExited?.Invoke( sender, process.ExitCode );
}
else
{
OnExited?.Invoke( sender, _process.ExitCode );
}
};
}
protected virtual void Start()
{
if ( _started )
{
return;
}
_started = true;
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
_process.WaitForExit();
}
public virtual async Task SendInput( string input )
{
try
{
await _process.StandardInput.WriteAsync( input! );
}
catch ( Exception e )
{
OnErrorDataReceived?.Invoke( _process, e.ToString() );
}
}
public virtual int Execute()
{
InitializeEvents();
Start();
return _process.ExitCode;
}
public virtual async Task<int> ExecuteAsync()
{
InitializeEvents();
return await Task.Run( () =>
{
Start();
return _process.ExitCode;
} )
.ConfigureAwait( false );
}
public virtual void Dispose()
{
_process.Dispose();
OnExited = null;
OnOutputDataReceived = null;
OnErrorDataReceived = null;
}
}
}