Here is a minimum reproducible problem:
public class Example
{
private readonly List<int> listToCollectResults = new();
private async Task SleepFor250msAndAppendToListAsync(int i)
{
await Task.Delay(250);
listToCollectResults.Add(i);
}
public void RunThis()
{
for (int i = 0; i < 100; i++)
{
SleepFor250msAndAppendToListAsync(i); // spin up N number of Tasks
}
Console.WriteLine(listToCollectResults.Count); // expect 0, since 250ms probably hasnt elapsed
Thread.Sleep(1000); // wait for all tasks to complete & appending to list, should be complete after this step
Console.WriteLine(listToCollectResults.Count); // missing some tasks?!
}
}
I get the following output:
0 // expected this
88 // why is it not 100
Why is it that there are 'missing' tasks?