using Sony.Filtr.Functional; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sony.Filtr.Utility.Extensions { public static class TaskExtensions { public static async Task> ToResult(this Task task) { try { return await task; } catch (Exception ex) { return Result.FromException(ex); } } public static void FireAndForget(this Task task) { // We don't want anything to happen here. } public static async Task EnsureAllSuccessAsync(this IEnumerable tasks) { await EnsureAllSuccessAsync(tasks, TaskScheduler.Current); } public static async Task EnsureAllSuccessAsync(this IEnumerable tasks, TaskScheduler taskScheduler) { if (tasks.Any()) { if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); await Task.WhenAll(tasks).ContinueWith(x => { if (x.Exception != null) { throw new InvalidOperationException( "Chain of tasks was not completed successfully. " + "Some of tasks are failed to complete. " + "See inner exception for more details.", x.Exception); } }, taskScheduler); } } public static void DoNotAwaitContinueWith(this Task task, Action continuation) { task.ContinueWith(continuation); } public static void DoNotAwait(this Task task) { } } }