Created
January 22, 2022 13:16
-
-
Save mrpmorris/963a081fe9ab31b00c3ccfa01f951f49 to your computer and use it in GitHub Desktop.
Task<T>.WithCancellationToken extension for async methods that do not accept a CancellationToken parameter
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
public static class TaskExtensions | |
{ | |
public static async Task<T?> WithCancellationToken<T>(this Task<T> source, CancellationToken cancellationToken) | |
{ | |
var cancellationTask = new TaskCompletionSource<bool>(); | |
cancellationToken.Register(() => cancellationTask.SetCanceled()); | |
_ = await Task.WhenAny(source, cancellationTask.Task); | |
if (cancellationToken.IsCancellationRequested) | |
return default; | |
return source.Result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment