I've been experimenting lately with async-await and I still cannot get some things to work.
Why does this code not always result with '100' being written to console?
Should not
await Task.WhenAll(tasks); wait for all 100 tasks to complete?
static List<int> list = new List<int>(); static void Main(string[] args) { NewMethod(); Console.ReadLine(); } private async static void NewMethod() { var tasks = new List<Task>(); for (int i = 0; i < 100; i++) { tasks.Add(Func(i)); } Console.WriteLine("Lol"); await Task.WhenAll(tasks); Console.WriteLine(list.Count()); } static async Task Func(int i) { await Task.Delay(100); list.Add(i); } Am I doing something wrong or is this some kind of async-await downside?
Same goes with
Task.WaitAll(tasks.ToArray()); which I wasn't sure at first if it's equal in this case.
There are a few similar questions but my example is really simple and I can't find explanation in the existing answers.