2

Why is this the case? If I remove the local variable within the for loop scope, it will print task 10 for all tasks, instead of 1-10.

class Program
    {

        public static void DoWork(int i)
        {
            Console.WriteLine("Task {0} starting", i);
            Thread.Sleep(2000);
            Console.WriteLine("Task {0} finished", i);

        }


        static void Main(string[] args)
        {
            Task[] Tasks = new Task[10];

            for (int i = 0; i < 10; i++)
            {
                int taskNum = i; // make a local copy of the loop counter so 
                                 // that correct task number is passed into 
                                 // the lambda expression
                Tasks[i] = Task.Run(() => DoWork(taskNum));
            }
            Task.WaitAll(Tasks);
            Console.WriteLine("Finished processing. Press a key to end.");
            Console.ReadKey();
        }


    }
FrankCastle616
  • 101
  • 1
  • 9
  • 2
    Because without the local variable, you're capturing `i` - not the value of `i`, but the variable itself. And by the time the loop has finished, the value of `i` is 10. So by the time the tasks have actually *started*, they'll be printing out 10. – Jon Skeet Mar 15 '19 at 19:30
  • Thanks guys. The more I think about it, it makes sense.The post you referred me to is spot on and explains it very clearly. Thanks again. – FrankCastle616 Mar 15 '19 at 19:39

0 Answers0