lagugula
lagugula

Reputation: 63

C# threading passing integer argument passes bad number

Good day to everyone. Today I made up a school project with one thing bothering me.

My problem is, that I am passing argument to Thread function and when I print it to console via Console.WriteLine, it shows bad numbers.

 for (i = 0; i < 10; i++) autari[i] = new Thread(() => autar(i));
 for (i = 0; i < 10; i++) motorkari[i] = new Thread(() => motorkar(i + 10));

When I start them in same cycles, their functions do this:

static void motorkar(int id)
    {
        Console.WriteLine("motorkar {0}", id);
        ...

It is not the order problem, but when I pass for example 0. Visual studio in Debug writes to console number 2 and without Debug it writes 1.

What can be the problem? I know that I can solve this by setting string name, but I am confused with this.

Upvotes: 1

Views: 195

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14456

This is due to the compiler creating you a closure under the hood. If you change the code around to the below you should get your expected output

for (i = 0; i < 10; i++)
{ 
    var local = i;
    autari[i] = new Thread(() => autar(local))
}

for (i = 0; i < 10; i++)
{
    var local = i + 10;
    motorkari[i] = new Thread(() => motorkar(local))
}

Upvotes: 4

Related Questions