WhenAll for .NET 3.5 I am trying to write a version of Task.WhenAll for .NET 3.5 using the "Task Parallel Library for .NET 3.5". This is what I came up with. Is there a better way of doing this?

    public static Task WhenAll(IEnumerable&lt;Task&gt; tasks)
    {
        var tcs = new TaskCompletionSource&lt;object&gt;();

        var remainingTasks = tasks.ToList();
        int count = remainingTasks.Count();
        var exceptions = new List&lt;Exception&gt;();

        foreach (var task in remainingTasks)
        {
            task.ContinueWith(t =&gt;
            {
                if (Interlocked.Decrement(ref count) == 0)
                {
                    foreach (var task1 in remainingTasks)
                    {
                        if (task1.IsFaulted)
                        {
                            exceptions.Add(task1.Exception);
                        }
                    }

                    if (exceptions.Any())
                    {
                        tcs.SetException(new AggregateException(exceptions));
                    }
                    else
                    {
                        tcs.SetResult(null);
                    }
                }
            });
        }

        return tcs.Task;
    }
int count = remainingTasks.Count();


Since remainingTasks is a List, you can use the Count property here.



var exceptions = new List&lt;Exception&gt;();


This variable should be declared where it's used: in the if Interlocked.Decrement block.



if (task1.IsFaulted)


This means you're treating canceled tasks the same as successfully completed ones. Instead, you can check whether Exception is null.

You could also rewrite the inner foreach using LINQ:

var exceptions = remainingTasks
    .Select(task =&gt; task.Exception)
    .Where(e =&gt; e != null)
    .ToList();