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

问题描述

我有3个任务:

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

他们都需要运行之前,我的code可以继续,我需要从每个结果也是如此。结果都没有什么共同点相互

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 ,您可以用出单独拉动的结果等待

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 (因为你知道凭这一点,他们都成功完成)。不过,我建议使用伺机,因为它显然是正确的,而结果可能会导致其他情况下的问题。

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.

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

06-30 02:30