Created
October 26, 2019 20:18
-
-
Save Daniel15/097c9a09bc804285da2eda8468d64474 to your computer and use it in GitHub Desktop.
C# WaitForExitAsync implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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