Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Task.WhenAll required in the sample code?

In the following code task1 and task2 are independent of each other and can run in parallel. What is the difference between following two implementations?

var task1 = GetList1Async();
var task2 = GetList2Async();

await Task.WhenAll(task1, task2);

var result1 = await task1; 
var result2 = await task2; 

and

var task1 = GetList1Async();
var task2 = GetList2Async();

var result1 = await task1; 
var result2 = await task2; 

Why should I choose one over the other?

Edit: I would like to add that return type of GetList1Async() and GetList2Async() methods are different.

like image 835
Snakebyte Avatar asked Sep 11 '13 17:09

Snakebyte


People also ask

What is the use of task WhenAll?

WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.

Does task WhenAll start the tasks?

WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

Does task WhenAll create new threads?

WhenAll does not create a new thread. A "task" does not necessarily imply a thread; there are two types of tasks: "event" tasks (e.g., TaskCompletionSource ) and "code" tasks (e.g., Task. Run ). WhenAll is an event-style task, so it does not represent code.


Video Answer


1 Answers

Your first example will wait for both tasks to complete and then retrieve the results of both.

Your second example will wait for the tasks to complete one at a time.

You should use whichever one is clearer for your code. If both tasks have the same result type, you can retrieve the results from WhenAll as such:

var results = await Task.WhenAll(task1, task2);
like image 131
Stephen Cleary Avatar answered Sep 25 '22 16:09

Stephen Cleary