Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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