1

I know Task.WaitAll(Task1,Task2) waits for all of the provided Task objects to complete execution.

What is Task.WhenAll used for?

Task.WhenAll in MSDN says

Creates a task that will complete when all of the supplied tasks have completed.

What is the real world scenario where once can apply Task.WhenAll()

Rockstart
  • 2,337
  • 5
  • 30
  • 59

2 Answers2

8

WaitAll blocks the calling thread while WhenAll provides a promise task that you can use to asynchronously wait using async-await without wasting up a thread in the meantime:

async Task ProcessAsync()
{
    await Task.WhenAll(DownloadAsync(), IntializeParserAsync(),...);
}

You should use WhenAll wherever you want to wait without having to block a thread, which improves scalability. (read: almost anywhere you can)

i3arnon
  • 113,022
  • 33
  • 324
  • 344
4

WaitAll is a void function that lets your code wait for completion of multiple tasks right away, at the time when you call it.

WhenAll, on the other hand, produces a Task that will wait for other tasks when it is its time to run. For example, if you are building a Task that needs to initialize a couple of things, and then run some computation, you can do it like this:

var initThenRun = Task
    .WhenAll(initTask1, initTask2, initTask3)
    .ContinueWith(computationTask);

Now the initThenRun task will run the three initialization tasks, wait for all of them to complete, and only then proceed to the computationTask.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • So what difference with `Task.Factory.ContinueWhenAll(new Task[]{initTask1, initTask2, initTask3}, computationTask)` – KevinBui Sep 18 '15 at 10:14
  • 1
    @KevinBui Since this is a different question, consider asking it as a question, not as a comment. This would give your question more visibility, potentially leading to much better answers. – Sergey Kalinichenko Sep 18 '15 at 11:59