public static Task WhenAllFast()

in Samples-NetCore/MusicManager/MusicManager.Domain/TaskUtility.cs [18:62]


        public static Task WhenAllFast(IEnumerable<Task> tasks)
        {
            if (tasks == null) { throw new ArgumentNullException(nameof(tasks)); }

            var tasksArray = tasks.ToArray();
            var taskCompletionSource = new TaskCompletionSource<object>();
            int count = tasksArray.Length;

            void ObserveException(Exception ex)
            {
                // Nothing to do.
            }

            foreach (var task in tasksArray)
            {
                task.ContinueWith(t =>
                {
                    if (taskCompletionSource.Task.IsCompleted)
                    {
                        ObserveException(t.Exception);
                        return;
                    }

                    if (t.IsCanceled)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else if (t.IsFaulted)
                    {
                        taskCompletionSource.TrySetException(t.Exception.Flatten().InnerExceptions);
                    }
                    else
                    {
                        // Decrement the count and continue if this was the last task.
                        if (Interlocked.Decrement(ref count) == 0)
                        {
                            taskCompletionSource.SetResult(null);
                        }
                    }

                }, TaskContinuationOptions.ExecuteSynchronously);
            }

            return taskCompletionSource.Task;
        }