creating new threads in a loop

前端 未结 2 1217
太阳男子
太阳男子 2020-12-12 01:30

I\'m trying to understand why this code is not working.

    private static object _lock;

    public static void Main (string[] args)
    {
        Thread th         


        
2条回答
  •  孤街浪徒
    2020-12-12 01:57

    Because each thread is refering to the loop variable, and does not get its own copy at the time you create the thread.

    Notice that the compiler is warning you: "Access to a modified closure".

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

提交回复
热议问题