Exemple #1
0
        private static Task <TResult> WhenAllCore <TResult>(IEnumerable <Task> tasks, Action <Task[], TaskCompletionSource <TResult> > setResultAction)
        {
            if (tasks == null)
            {
                throw new ArgumentNullException("tasks");
            }
            TaskCompletionSource <TResult> tcs = new TaskCompletionSource <TResult>();

            Task[] tasks1 = tasks as Task[] ?? tasks.ToArray <Task>();
            if (tasks1.Length == 0)
            {
                setResultAction(tasks1, tcs);
            }
            else
            {
                Task.Factory.ContinueWhenAll(tasks1, (Action <Task[]>)(completedTasks =>
                {
                    List <Exception> targetList = (List <Exception>)null;
                    bool flag = false;
                    foreach (Task completedTask in completedTasks)
                    {
                        if (completedTask.IsFaulted)
                        {
                            TaskEx.AddPotentiallyUnwrappedExceptions(ref targetList, (Exception)completedTask.Exception);
                        }
                        else if (completedTask.IsCanceled)
                        {
                            flag = true;
                        }
                    }
                    if (targetList != null && targetList.Count > 0)
                    {
                        tcs.TrySetException((IEnumerable <Exception>)targetList);
                    }
                    else if (flag)
                    {
                        tcs.TrySetCanceled();
                    }
                    else
                    {
                        setResultAction(completedTasks, tcs);
                    }
                }), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            }
            return(tcs.Task);
        }