Last active
December 9, 2021 12:46
-
-
Save joe-oli/65c2a975e227b9d2ad575b2938ad9a8b to your computer and use it in GitHub Desktop.
C# Process WaitForExit
This file contains hidden or 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
/// <summary> | |
/// Waits asynchronously for the process to exit. | |
/// </summary> | |
/// <param name="process">The process to wait for cancellation.</param> | |
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return | |
/// immediately as canceled.</param> | |
/// <returns>A Task representing waiting for the process to end.</returns> | |
public static Task WaitForExitAsync(this Process process, | |
CancellationToken cancellationToken = default(CancellationToken)) | |
{ | |
if (process.HasExited) return Task.CompletedTask; | |
var tcs = new TaskCompletionSource<object>(); | |
process.EnableRaisingEvents = true; | |
process.Exited += (sender, args) => tcs.TrySetResult(null); | |
if(cancellationToken != default(CancellationToken)) | |
cancellationToken.Register(() => tcs.SetCanceled()); | |
return process.HasExited ? Task.CompletedTask : tcs.Task; | |
} | |
/* USAGE: | |
public async void Test() | |
{ | |
var process = new Process("processName"); | |
process.Start(); | |
await process.WaitForExitAsync(); | |
//Do some fun stuff here... | |
} | |
COMMENT: | |
Beware, if you pass through WaitForExitAsync some CancellationToken, that will be automatically canceled after the specified delay, you can get an InvalidOperationException. To fix that, you need to change | |
cancellationToken.Register(tcs.SetCanceled); | |
to | |
cancellationToken.Register( () => { tcs.TrySetCanceled(); } ); | |
Also,don't forget to dispose your CancellationTokenSource in time. | |
From here: | |
https://stackoverflow.com/questions/470256/process-waitforexit-asynchronously | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment