for循环内的Lambda表达式

时间:2019-03-15 19:29:08

标签: c# for-loop lambda task

为什么会这样?如果我在for循环范围内删除了局部变量,它将为所有任务打印任务10,而不是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();
        }


    }

0 个答案:

没有答案