1

I'm new to multithreading and i'm having unexpected results with a very simple code:

    public void Run()
    {
        for (int i = 0; i < 10; i++)
        {
            Thread t = new Thread(() => myFun((i + 1)));
            t.Start();
        }
    }

    private void myFun(int threadNo)
    {
        Console.WriteLine("Thread #" + threadNo.ToString());
    }

Can someone explain me why the code above prints this to the console window ?

Thread #3

Thread #3

Thread #3

Thread #6

Thread #6

Thread #8

Thread #9

Thread #10

Thread #11

Thread #11

Jonathan
  • 1,276
  • 10
  • 35

2 Answers2

4

It's because you're using a lambda which closes over the loop variable.

Restructure your code as such:

public void Run()
{
    for (int i = 0; i < 10; i++)
    {
        int j = i;
        Thread t = new Thread(() => myFun((j + 1)));
        t.Start();
    }
}

private void myFun(int threadNo)
{
    Console.WriteLine("Thread #" + threadNo.ToString());
}

and enjoy the change.

Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
0

You could either use a "local" variable inside the loop like Jesse suggested, or you could instead use a parameterized start (ParameterizedThreadStart):

public void Run()
{
    for (int i = 0; i < 10; i++)
    {
        Thread t = new Thread(myFun);
        t.Start(i + 1);
    }
}

private void myFun(object threadNo)
{
    Console.WriteLine("Thread #" + threadNo.ToString());
}
Amit
  • 45,440
  • 9
  • 78
  • 110