Is Task.WhenAll required in the sample code?

2019-04-08 03:39发布

问题:

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.

回答1:

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);


回答2:

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

Also less writing, if you add a 3rd or 4th task... I.e. :

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

compared to:

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