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.
WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.
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.
WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With