I have 3 tasks:
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
How do I call and await for the 3 tasks to complete and then get the results?
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;
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.