patterncsharpCritical
Awaiting multiple Tasks with different results
Viewed 0 times
withtasksmultipleawaitingdifferentresults
Problem
I have 3 tasks:
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?
private async Task FeedCat() {}
private async Task SellHouse() {}
private async Task 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?
Solution
After you use
[Note that asynchronous methods always return "hot" (already started) tasks.]
You can also 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;[Note that asynchronous methods always return "hot" (already started) tasks.]
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.Code Snippets
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;Context
Stack Overflow Q#17197699, score: 739
Revisions (0)
No revisions yet.