tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Waiting for process to exit without blocking

15 Oct 2015 1 mins .NET, C#, Multithreading/Parallelism/Asynchronous/Concurrency

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 CancelationTokens if you you need those. It will make the code bit less straightforward, though.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.