I'm testing a piece of code where a the same Task should be executed in a for loop, with variables updated every cycle.
for (int j = 0; j < 6; j++)
{
_waitNextBatch++;
Console.WriteLine($"{_waitNextBatch}");
BatchSensor bs = new BatchSensor { SensorName = $"batch - {j}" };
new Thread(() => SimulateBS(bs, j)).Start();
}
In the method called by the Task I get the correct bs
, but the j
is the last iteration value for all the runs.
I just print the values received from the SimulateBS
method
Console.WriteLine($"{bs.SensorName} | {j}");
And I get as output:
batch - 0 | 6
batch - 2 | 6
batch - 5 | 6
batch - 4 | 6
batch - 3 | 6
batch - 1 | 6
or
batch - 0 | 2
batch - 1 | 3
batch - 2 | 3
batch - 3 | 5
batch - 4 | 5
batch - 5 | 6
Any idea why is this happening?