Difference between async loops in C#

What do you think will happen when you run these 2 snippets of code? They both looks quite similar at the first sight, don’t they. This one var results = new List<SomeClass>(); mylist.ForEach(async item => { var result = await SomeDbQueryAsync(item); results.Add(result); }); versus this one var results = new List<SomeClass>(); foreach(var item in mylist) { var result = await SomeDbQueryAsync(item); results.Add(result); }); The code looks remarkably similar, but the 1st sample will throw this exception “A second operation started on this context before a previous asynchronous operation completed. Use ‘await’ to ensure that any asynchronous operations have completed before …

Continue Reading