I have a following task: execute multiple asynchronous methods synchronously and always execute them all, even when one of them throws. Rethrow thrown exceptions if any occured only after all tasks have finished. Here is my code:
public static async Task ContinueWithoutThrowing(this IEnumerable<Func<Task>> tasks)
{
var thrownExceptions = new List<Exception>();
foreach (var task in tasks)
{
try
{
await task().ConfigureAwait(false);
}
catch (Exception ex)
{
thrownExceptions.Add(ex);
}
}
if (thrownExceptions.Any())
{
throw new AggregateException(thrownExceptions);
}
}
Usage of this code is following:
Func<Task>[] tasks = { First, Second };
await tasks.ContinueWithoutThrowing().ConfigureAwait(false);
I am not sure whether what I am doing is accomplishable using already implemented methods on Task class like WhenAll. But using WhenAll with await throws on first exception. Also couldn't figure out some better name than ContinueWithoutThrowing when it actually throws if used with await (but its wanted behavior). I know this code doesn't handle cancellation but its not my main concern right now.