Michael Brennt Michael Brennt - 25 days ago 12
C# Question

await Task.WhenAll does not wait for all tasks to complete

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)

private async static void NewMethod()
var tasks = new List<Task>();
for (int i = 0; i < 100; i++)


await Task.WhenAll(tasks);


static async Task Func(int i)
await Task.Delay(100);

Am I doing something wrong or is this some kind of async-await downside?

Same goes with


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.


The reason you experience the inconsistency in the number of elements is because List<T> isn't thread-safe.

After you await Task.Delay(100), the continuation, which adds elements to the list happens on an arbitrary thread pool, concurrently, because multiple tasks are executing. If you switch you implementation to use ConcurrentBag<int>, this wont happen.