Last active
August 28, 2022 04:26
-
-
Save emoacht/a333e9243cd9b52d2e2a122d9730e883 to your computer and use it in GitHub Desktop.
Aynchronously numerate Task results with timeout and cancellation.
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
public static class TaskHelper | |
{ | |
public static async Task<IEnumerable<TResult>> EnumerateTaskResults<TResult>(IEnumerable<Func<TResult>> source, TimeSpan timeout, CancellationToken cancellationToken) | |
{ | |
var enumerateTasks = source | |
.Select(x => Task.Run(() => x.Invoke())) | |
.ToArray(); | |
var timeoutTask = Task.Delay(timeout, cancellationToken); | |
await Task.WhenAny(Task.WhenAll(enumerateTasks), timeoutTask); | |
cancellationToken.ThrowIfCancellationRequested(); | |
return enumerateTasks | |
.Where(x => x.Status == TaskStatus.RanToCompletion) | |
.Select(x => x.Result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment