等待具有不同结果的多个任务 [英] Awaiting multiple Tasks with different results

查看:29
本文介绍了等待具有不同结果的多个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个任务:

private async Task<Cat> FeedCat() {}
private async Task<House> SellHouse() {}
private async Task<Tesla> BuyCar() {}

在我的代码可以继续之前,它们都需要运行,我也需要每个的结果.结果没有任何共同点

They all need to run before my code can continue and I need the results from each as well. None of the results have anything in common with each other

如何调用并等待 3 个任务完成然后获取结果?

How do I call and await for the 3 tasks to complete and then get the results?

推荐答案

使用 WhenAll 后,可以使用 await 单独拉出结果:

After you use WhenAll, you can pull the results out individually with await:

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

await Task.WhenAll(catTask, houseTask, carTask);

var cat = await catTask;
var house = await houseTask;
var car = await carTask;

您也可以使用 Task.Result(因为您知道此时它们都已成功完成).但是,我建议使用 await 因为它显然是正确的,而 Result 在其他情况下可能会导致问题.

You can also use Task.Result (since you know by this point they have all completed successfully). However, I recommend using await because it's clearly correct, while Result can cause problems in other scenarios.

这篇关于等待具有不同结果的多个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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