I have pretty simple piece of code:
public class CustomTester
{
public async Task RunTheTestAsync()
{
IList<int> someCollectionToFill = new List<int>();
var someCollectionToIterate = Enumerable.Range(0, 20);
IEnumerable<Task> tasks = someCollectionToIterate.Select(
valueFromCollection => Task.Run(async () =>
{
try
{
await Task.Delay(1);
someCollectionToFill.Add(valueFromCollection);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
})).ToList();
await Task.WhenAll(tasks);
PrintCollectionValues(someCollectionToFill);
}
private void PrintCollectionValues(IList<int> collection)
{
Console.WriteLine("Total count: " + collection.Count);
}
}
I am executing it like this:
await new CustomTester().RunTheTestAsync();
When the code executed, I have following output:
Total count: 13
or:
Total count: 14
etc...
But I am expecting:
Total count: 20
Why is this happening?