Is Task.WhenAll required in the sample code?

最后都变了- 提交于 2019-12-21 12:17:59

问题


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; 


来源:https://stackoverflow.com/questions/18747213/is-task-whenall-required-in-the-sample-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!