4

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();
}

}

enter image description here

Community
  • 1
  • 1
Anand
  • 1,335
  • 1
  • 12
  • 20
  • 2
    That's becuase lambda expression closes over the for loop variable. do this `for (i = 0; i < 10; i++) { var t=i; Thread th1 = new Thread(()=>tone(t) );` – Royi Namir May 19 '14 at 10:52

1 Answers1

7

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);
    }
Community
  • 1
  • 1
Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59