Is Task.WhenAll required in the sample code?

In the following code, task1 and task2 are independent of each other and can be executed in parallel. What is the difference between the 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 by one?

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

+6
source share
2 answers

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

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

You should use what is best for your code. If both tasks have the same type of result, you can get results from WhenAll as such:

 var results = await Task.WhenAll(task1, task2); 
+9
source

The first design is more readable. You clearly state that you intend to wait for the completion of all tasks before obtaining results. I find it reasonable enough to use this instead of the second.

Also write less if you add a third or fourth task ... That is:

 await Task.WhenAll(task1, task2, task3, task4); 

compared with:

 var result1 = await task1; var result2 = await task2; var result3 = await task3; var result4 = await task4; 
+1
source

Source: https://habr.com/ru/post/953644/


All Articles