Why do I get unexpected output when spawning threads?

I tried to create a certain number of threads. But when I pass the arguments to the function, the output is random. It selects the values ​​of the variable "i" several times and ignores some. I am new to C #. Please explain if I am not doing something wrong.

using System;
using System.Threading;

public class first
{
     public static void tone(int i)
{
        Console.WriteLine("Hi ! this is thread : {0} ",i);
        Thread.Sleep(10);
}

public static void Main(String[] args)
{
    int i;
    for (i = 0; i < 10; i++)
    {
        Thread th1 = new Thread(()=>tone(i) );
        th1.Start();
       // Console.WriteLine(i);
    }
    Console.WriteLine("hey there!");
    Console.ReadLine();
}

}

enter image description here

+4
source share
1 answer

Due to closure :

Change your code to:

int i;
    for (i = 0; i < 10; i++)
    {
       int j = i;
        Thread th1 = new Thread(()=>tone(j) );
        th1.Start();
       // Console.WriteLine(i);
    }
+7
source

Source: https://habr.com/ru/post/1541102/


All Articles