Created
January 24, 2020 17:18
-
-
Save benaadams/7309c7c095b174fedf50aaee210d715b to your computer and use it in GitHub Desktop.
WhenAllIgnoreErrors from https://twitter.com/fquednau/status/1220747346973200384
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 TaskExtensions | |
{ | |
public static async Task<T[]> WhenAllIgnoreErrors<T>(this Task<T>[] tasks, TimeSpan timeout) | |
{ | |
try | |
{ | |
await Task.WhenAll(tasks).TimeoutAfter(timeout).ConfigureAwait(false); | |
} | |
catch { /* ignored */ } | |
List<T> results = new List<T>(); | |
foreach (var task in tasks) | |
{ | |
if (task.IsCompletedSuccessfully) | |
{ | |
results.Add(task.Result); | |
} | |
else | |
{ | |
Ignore(task.Exception); | |
} | |
} | |
return results.ToArray(); | |
static void Ignore(Exception? ex) { } | |
} | |
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) | |
{ | |
var cts = new CancellationTokenSource(); | |
if (task == await Task<TResult>.WhenAny(task, Task<TResult>.Delay(timeout, cts.Token)).ConfigureAwait(false)) | |
{ | |
cts.Cancel(); | |
return await task.ConfigureAwait(false); | |
} | |
else | |
{ | |
throw new TimeoutException($"Task timed out after {timeout}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment