Fixed example 2 so that its runnable (#22328)

added some some time consuming code and a return to `CalcDamage`
removed `static` from `CalcTotalDamage` so that the compiler doesn't complain that `CalcDamage` should be static
compiler wasn't happy with `totalDamage += CalcDamage(player);` or `return await Task.WhenAll(totalDamage)` because you are attempting to assign a Task to an int. Fixed it by using `WhenAll` correctly
Changed parameter name of `CalcTotalDamage` from `group` to `people` as  `group` can  be confusing to read as its used with linq
pull/30085/head^2
justingiffard 2019-02-25 03:36:06 +02:00 committed by Christopher McCormack
parent f224bbc62f
commit 97834c64d2
1 changed files with 10 additions and 5 deletions

View File

@ -41,20 +41,25 @@ public async Task<int> CalcDamage(Player player)
// Boss based on the damage types, Boss stats (from static data),
// player stats, etc.
// ...
await Task.Delay(1000); // extemely time consuming calculation
return 3; // that calculates a very accurate damage thats not hardcoded at all
}
public static async Task<int> CalcTotalDamage(IEnumerable<Player> group)
public async Task<int> CalcTotalDamage(IEnumerable<Player> players)
{
var totalDamage = 0;
foreach (Player player in group)
var tasks = new List<Task<int>>();
foreach (Player player in players)
{
// each of the async methods are queued in the thread-pool and move on.
totalDamage += CalcDamage(player);
var t = CalcDamage(player);
// storing reference to the task
tasks.Add(t);
}
// total damage done must be calculated from all players in the group
// before we return the result.
return await Task.WhenAll(totalDamage);
var completeTask = await Task.WhenAll(tasks);
return completeTask.Sum();
}
```