0

I am trying to make a List of Threads but I am getting very weird results, if I add the threads manually every thing works fine like that:

    static void WriteM(int m)
    {
        for (long i = 0; i < 3; i++)
        {
            Console.WriteLine(m);
        }
    }
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        threads.Add(new Thread(() => WriteM(0)));
        threads.Add(new Thread(() => WriteM(1)));
        threads.Add(new Thread(() => WriteM(2)));
        threads.Add(new Thread(() => WriteM(3)));
        foreach (Thread t in threads)
        {
            t.Start();
        }
    }

I get this output

0
0
0
1
1
1
3
3
3
2
2
2

but if I use for Loop to add the Threads I get this weird results

    static void WriteM(int m)
    {
        for (long i = 0; i < 3 ; i++)
        {         
                Console.WriteLine(m);
        }
    }
    static void Main(string[] args)
    {                     
        List<Thread> threads = new List<Thread>();
        for (inti = 0;i<4;i++)
        {
            threads.Add(new Thread(() => Do(i)));
        }
        
        foreach (Thread t in threads)
        {
            t.Start();
        }
    }

output

4
4
4
4
4
4
4
4
4
4
4
4

its actually the max value of i in the loop +1

can someone tell me what is that happening?

  • In the first example, you are using integer literals. In the second example, you are using an iteration variable `i`, and the lamda functions are capturing that variable in a closure. That's the difference. – JLRishe Jan 02 '22 at 17:03

0 Answers0