.NET 4 equivalent of Task.WhenAll()
Asked Answered
B

3

16

In .NET 4, is there any functional equivalent to .NET 4.5's System.Threading.Tasks.Task.WhenAll()?

The goal is to wrap up multiple async tasks into a single one that is completed when all of its constituent tasks are done.

Baddie answered 16/7, 2012 at 21:7 Comment(4)
@L.B Parallel.Invoke doesn't operate on Tasks, it operates on Actions.Jahdai
@MonroeThomas, So Is it forbidden to use Actions? And as you can see I posted as a comment not as an answer.Skunk
@Skunk I would venture that Actions are not appropriate here because the OP has explicitly stated async tasks, and has reinforced that by specifying that he wants the signature and behaviour of Task.WhenAll, which only accepts IEnumerable<Task>. Parallel.Invoke does not return a Task, which the OP is also looking for.Jahdai
Can you just use the async targeting pack? Not sure if it contains that or not off-handLaciniate
J
17

I think the closest thing built-in in .Net 4.0 is ContinueWhenAll(). You can make the continuationAction a simple tasks => tasks and use the returned Task.

For performance reasons, you might want to use it with TaskContinuationOptions.ExecuteSynchronously.

Jail answered 16/7, 2012 at 21:41 Comment(1)
@MonroeThomas, thanks for that excellent link - the Task.Factory extensions are very handy, and the rest of the parallel programming examples look fascinating.Baddie
K
27

In .NET Framework 4.0 WhenAll and WhenAny can be used with installed AsyncCTP in case of Visual Studio 2010 or Async Targeting Pack in case of Visual Studio 2012.

The WhenAll and WhenAny methods are then offered on the TaskEx type.

Keynesianism answered 19/8, 2012 at 12:28 Comment(2)
This should be the top answer, IMO.Necker
i can't found WhenAll eventhough i installed AsyncCTP for VS 2010.Muffin
J
17

I think the closest thing built-in in .Net 4.0 is ContinueWhenAll(). You can make the continuationAction a simple tasks => tasks and use the returned Task.

For performance reasons, you might want to use it with TaskContinuationOptions.ExecuteSynchronously.

Jail answered 16/7, 2012 at 21:41 Comment(1)
@MonroeThomas, thanks for that excellent link - the Task.Factory extensions are very handy, and the rest of the parallel programming examples look fascinating.Baddie
J
2

Try waiting on Task.WaitAll() in another Task. Use the LINQ extension method ToArray to convert from IEnumerable<Task> to Task[].

Task WhenAll(IEnumerable<Task> tasks)
{
    return Task.Factory.StartNew(() => Task.WaitAll(tasks.ToArray()));
}
Jahdai answered 16/7, 2012 at 21:18 Comment(1)
Agreed. Your answer is better. Thanks!Jahdai

© 2022 - 2024 — McMap. All rights reserved.