In the following code block:
static void Main(string[] args)
{
List<int> arr00 = new List<int>() {100, 0, 3, 8, 21};
int index = 0;
int tasks = 0;
foreach (int num in arr00)
{
var innerIndex = index;
Task.Run(async () =>
{
Console.WriteLine($"{index}, {innerIndex}: {num}");
tasks++;
});
index++;
}
while (tasks < index) { }
}
The output is
5, 1: 0
5, 4: 21
5, 2: 3
5, 3: 8
5, 0: 100
How did the async task keep the correct count for innerIndex, but not the hoisted index?
Thanks