Waiting for process to exit without blocking
I have been scripting something in build process of one big project where to make the final binaries bunch of other tools need to be executed. Given that this was in pipeline where most of steps were asynchronous I was eager to have this non-blocking as well and possibly introduce parallelism.
The problem is that the Process
class has only WaitForExit
method, blocking. Luckily there’s a OnExited
event. Using it I can construct TaskCompletionSource
and signal it completed when the process exits. Here’s the extension ready to be used.
public static Task WaitForExitAsync(this Process p)
{
p.EnableRaisingEvents = true;
var tcs = new TaskCompletionSource<object>();
p.Exited += (s, e) => tcs.TrySetResult(null);
if (p.HasExited)
tcs.TrySetResult(null);
return tcs.Task;
}
You can plug timeouts or CancelationToken
s if you you need those. It will make the code bit less straightforward, though.