From 97834c64d2c7948533f2a9ab8dda456ef03865d5 Mon Sep 17 00:00:00 2001 From: justingiffard Date: Mon, 25 Feb 2019 03:36:06 +0200 Subject: [PATCH] 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 --- guide/english/csharp/async-await/index.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/guide/english/csharp/async-await/index.md b/guide/english/csharp/async-await/index.md index fa349ee99d5..6d0266a26e7 100644 --- a/guide/english/csharp/async-await/index.md +++ b/guide/english/csharp/async-await/index.md @@ -41,20 +41,25 @@ public async Task 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 CalcTotalDamage(IEnumerable group) +public async Task CalcTotalDamage(IEnumerable players) { - var totalDamage = 0; - foreach (Player player in group) + var tasks = new List>(); + 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(); } ```