Skip to content

Instantly share code, notes, and snippets.

@Daniel15
Created October 26, 2019 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel15/097c9a09bc804285da2eda8468d64474 to your computer and use it in GitHub Desktop.
Save Daniel15/097c9a09bc804285da2eda8468d64474 to your computer and use it in GitHub Desktop.
C# WaitForExitAsync implementation
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Daniel15.Extensions
{
/// <summary>
/// Extensions for <see cref="Process"/>
/// </summary>
public static class ProcessExtensions
{
/// <summary>
/// Asynchronously waits for the process to exit.
/// </summary>
public static async Task<int> WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<int>();
void ExitHandler(object sender, EventArgs e) => tcs.TrySetResult(process.ExitCode);
int exitCode;
try
{
process.EnableRaisingEvents = true;
process.Exited += ExitHandler;
if (process.HasExited)
{
tcs.TrySetResult(process.ExitCode);
}
await using (cancellationToken.Register(() => tcs.TrySetCanceled()))
{
exitCode = await tcs.Task.ConfigureAwait(false);
}
}
finally
{
process.Exited -= ExitHandler;
}
return exitCode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment