示例代码中是否需要Task.WhenAll? [英] Is Task.WhenAll required in the sample code?

查看:65
本文介绍了示例代码中是否需要Task.WhenAll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,task1和task2彼此独立,可以并行运行.以下两种实现之间有什么区别?

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; 

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

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

为什么我要选择一个?

我想补充一下,GetList1Async()和GetList2Async()方法的返回类型是不同的.

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

推荐答案

您的第一个示例将等待两个任务完成,然后检索这两个任务的结果.

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.

您应该使用更清晰的代码之一.如果两个任务具有相同的结果类型,则可以这样从WhenAll检索结果:

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

这篇关于示例代码中是否需要Task.WhenAll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆