Why am I getting unexpected output when spawning threads?

.net, c#, multithreading

Solution

Because of 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);
    }

Problem

I was trying to spawn certain number of threads. But when I pass arguments to the function the output is random. It chooses some values of variable 'i' for multiple times and ignores some. I am a newbie in C#. Please explain if I am doing anything 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(); } ``` }

Original source

Related problems