@@ -13,10 +13,14 @@ public sealed class MxcExecutor
1313{
1414 private const int DefaultStdoutCapBytes = 40_000 ;
1515 private const int DefaultStderrCapBytes = 5_000 ;
16+ private static readonly TimeSpan s_defaultCleanupTimeout = TimeSpan . FromMilliseconds ( 500 ) ;
1617
1718 private readonly string _wxcExePath ;
1819 private readonly int _stdoutCapBytes ;
1920 private readonly int _stderrCapBytes ;
21+ private readonly Func < ProcessStartInfo , Process > _processFactory ;
22+ private readonly Action < Process > _processTreeKiller ;
23+ private readonly TimeSpan _cleanupTimeout ;
2024
2125 private static readonly JsonSerializerOptions s_jsonOptions = new ( )
2226 {
@@ -25,13 +29,38 @@ public sealed class MxcExecutor
2529 } ;
2630
2731 public MxcExecutor ( string wxcExePath , int ? stdoutCapBytes = null , int ? stderrCapBytes = null )
32+ : this (
33+ wxcExePath ,
34+ stdoutCapBytes ,
35+ stderrCapBytes ,
36+ static startInfo => new Process { StartInfo = startInfo } ,
37+ static process => process . Kill ( entireProcessTree : true ) ,
38+ s_defaultCleanupTimeout )
39+ {
40+ }
41+
42+ internal MxcExecutor (
43+ string wxcExePath ,
44+ int ? stdoutCapBytes ,
45+ int ? stderrCapBytes ,
46+ Func < ProcessStartInfo , Process > processFactory ,
47+ Action < Process > processTreeKiller ,
48+ TimeSpan cleanupTimeout )
2849 {
2950 if ( string . IsNullOrEmpty ( wxcExePath ) ) throw new ArgumentException ( "wxcExePath required" , nameof ( wxcExePath ) ) ;
3051 if ( ! File . Exists ( wxcExePath ) )
3152 throw new FileNotFoundException ( $ "wxc-exec.exe not found at: { wxcExePath } ", wxcExePath ) ;
53+ ArgumentNullException . ThrowIfNull ( processFactory ) ;
54+ ArgumentNullException . ThrowIfNull ( processTreeKiller ) ;
55+ if ( cleanupTimeout <= TimeSpan . Zero )
56+ throw new ArgumentOutOfRangeException ( nameof ( cleanupTimeout ) , "Cleanup timeout must be positive." ) ;
57+
3258 _wxcExePath = wxcExePath ;
3359 _stdoutCapBytes = stdoutCapBytes is > 0 ? stdoutCapBytes . Value : DefaultStdoutCapBytes ;
3460 _stderrCapBytes = stderrCapBytes is > 0 ? stderrCapBytes . Value : DefaultStderrCapBytes ;
61+ _processFactory = processFactory ;
62+ _processTreeKiller = processTreeKiller ;
63+ _cleanupTimeout = cleanupTimeout ;
3564 }
3665
3766 public async Task < MxcResult > RunAsync (
@@ -78,7 +107,6 @@ private async Task<MxcResult> RunWithArgumentsAsync(
78107 CancellationToken ct ,
79108 string ? workingDirectory )
80109 {
81- using var process = new Process ( ) ;
82110 var startInfo = new ProcessStartInfo
83111 {
84112 FileName = _wxcExePath ,
@@ -94,18 +122,27 @@ private async Task<MxcResult> RunWithArgumentsAsync(
94122 // ArgumentList avoids the manual-quoting trap that bites Process.Arguments
95123 // (each entry is escaped per Win32 CommandLineToArgvW rules by the BCL).
96124 foreach ( var arg in arguments ) startInfo . ArgumentList . Add ( arg ) ;
97- process . StartInfo = startInfo ;
125+ using var process = _processFactory ( startInfo )
126+ ?? throw new InvalidOperationException ( "Process factory returned null." ) ;
98127
99128 var stdoutBuilder = new StringBuilder ( ) ;
100129 var stderrBuilder = new StringBuilder ( ) ;
101130 // StringBuilder is not thread-safe; the async event handlers can fire
102131 // concurrently with each other and with the post-kill ToString() read.
103132 var outLock = new object ( ) ;
104133 var errLock = new object ( ) ;
134+ var processExited = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
135+ var stdoutClosed = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
136+ var stderrClosed = new TaskCompletionSource ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
105137
106138 process . OutputDataReceived += ( _ , e ) =>
107139 {
108- if ( e . Data is null ) return ;
140+ if ( e . Data is null )
141+ {
142+ stdoutClosed . TrySetResult ( ) ;
143+ return ;
144+ }
145+
109146 lock ( outLock )
110147 {
111148 if ( stdoutBuilder . Length < _stdoutCapBytes * 2 )
@@ -114,25 +151,34 @@ private async Task<MxcResult> RunWithArgumentsAsync(
114151 } ;
115152 process . ErrorDataReceived += ( _ , e ) =>
116153 {
117- if ( e . Data is null ) return ;
154+ if ( e . Data is null )
155+ {
156+ stderrClosed . TrySetResult ( ) ;
157+ return ;
158+ }
159+
118160 lock ( errLock )
119161 {
120162 if ( stderrBuilder . Length < _stderrCapBytes * 2 )
121163 stderrBuilder . AppendLine ( e . Data ) ;
122164 }
123165 } ;
166+ process . EnableRaisingEvents = true ;
167+ process . Exited += ( _ , _ ) => processExited . TrySetResult ( ) ;
124168
125169 var sw = Stopwatch . StartNew ( ) ;
126170 try
127171 {
128172 process . Start ( ) ;
129173 process . BeginOutputReadLine ( ) ;
130174 process . BeginErrorReadLine ( ) ;
175+ if ( process . HasExited )
176+ processExited . TrySetResult ( ) ;
131177
132178 bool completed ;
133179 try
134180 {
135- await process . WaitForExitAsync ( ct ) ;
181+ await processExited . Task . WaitAsync ( ct ) ;
136182 completed = true ;
137183 }
138184 catch ( OperationCanceledException )
@@ -142,13 +188,11 @@ private async Task<MxcResult> RunWithArgumentsAsync(
142188
143189 if ( ! completed )
144190 {
145- try { process . Kill ( entireProcessTree : true ) ; }
191+ try { _processTreeKiller ( process ) ; }
146192 catch ( Exception ex ) { Trace . WriteLine ( $ "MxcExecutor: process kill (cancellation path) failed: { ex . Message } ") ; }
147- // WaitForExit() (sync) blocks until both stdout and stderr async
148- // readers have drained the redirected pipes. Without this the
149- // event handlers can still be appending while ToString() runs.
150- try { process . WaitForExit ( ) ; }
151- catch ( Exception ex ) { Trace . WriteLine ( $ "MxcExecutor: process drain (cancellation path) failed: { ex . Message } ") ; }
193+ if ( ! await WaitForCleanupAsync ( processExited . Task , stdoutClosed . Task , stderrClosed . Task , _cleanupTimeout ) )
194+ Trace . WriteLine ( "MxcExecutor: cancellation cleanup timed out." ) ;
195+
152196 sw . Stop ( ) ;
153197 string capturedOut ;
154198 lock ( outLock ) { capturedOut = stdoutBuilder . ToString ( ) ; }
@@ -163,9 +207,9 @@ private async Task<MxcResult> RunWithArgumentsAsync(
163207 } ;
164208 }
165209
166- // Flush async readers before reading the StringBuilders.
167- try { process . WaitForExit ( ) ; }
168- catch ( Exception ex ) { Trace . WriteLine ( $ "MxcExecutor: post-exit drain WaitForExit failed: { ex . Message } " ) ; }
210+ if ( ! await WaitForCleanupAsync ( processExited . Task , stdoutClosed . Task , stderrClosed . Task , _cleanupTimeout ) )
211+ Trace . WriteLine ( "MxcExecutor: post-exit output drain timed out." ) ;
212+
169213 sw . Stop ( ) ;
170214 string outRaw , errRaw ;
171215 lock ( outLock ) { outRaw = stdoutBuilder . ToString ( ) . Trim ( ) ; }
@@ -196,6 +240,23 @@ private async Task<MxcResult> RunWithArgumentsAsync(
196240 }
197241 }
198242
243+ internal static async Task < bool > WaitForCleanupAsync (
244+ Task processExited ,
245+ Task stdoutClosed ,
246+ Task stderrClosed ,
247+ TimeSpan timeout )
248+ {
249+ try
250+ {
251+ await Task . WhenAll ( processExited , stdoutClosed , stderrClosed ) . WaitAsync ( timeout ) ;
252+ return true ;
253+ }
254+ catch ( TimeoutException )
255+ {
256+ return false ;
257+ }
258+ }
259+
199260 private static string Truncate ( string text , int maxLength )
200261 {
201262 if ( text . Length <= maxLength ) return text ;
0 commit comments