-2

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

C-Trouble
  • 21
  • 2
  • Take a look at this: [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp). – Theodor Zoulias Feb 29 '20 at 21:38

1 Answers1

0

The foreach loop starts a task completes iteration starts another task in next iteration and so on. The fareach completes all iteration and sets value of index as 5 even before 1st task starts. That's why you find value of index as 5 for all tasks. Now if you add a Wait each task to complete then value of index and innerIndex will match. But you will loos the advantage of executing those task in parallel.

Change the code as:

foreach (int num in arr00)
{
    var innerIndex = index;
    Task.Run(async () =>
    {
        Console.WriteLine($"{index}, {innerIndex}: {num}");
        tasks++;
    }).Wait();  //Wait for task to complete

    index++;
}

Output:

0, 0: 100
1, 1: 0
2, 2: 3
3, 3: 8
4, 4: 21
MKR
  • 19,739
  • 4
  • 23
  • 33