在循环中创建新线程

Leo*_*eon 2 c# multithreading

我试图理解为什么这段代码不起作用.

    private static object _lock;

    public static void Main (string[] args)
    {
        Thread thread;
        _lock = new object();

        foreach (int num in Enumerable.Range(0,5)) {
            thread  = new Thread (() => print(num.ToString()));
            thread.Start(); 
        }
    }

    public static void print(string text)
    {
        lock(_lock)
        {
            Console.WriteLine(text);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我最终输出了

4 1 4 4 3

或任何其他随机数字的数字.为什么重复数字?

Mit*_*eat 5

因为每个线程都引用了循环变量,并且在创建线程时没有获得自己的副本.

请注意,编译器警告您:" 访问已修改的闭包 ".

    foreach (int num in Enumerable.Range(0,5))
    {
        int loopnum = num;

        thread = new Thread(() => print(loopnum.ToString())); 
        thread.Start();  
    }
Run Code Online (Sandbox Code Playgroud)