I have the following C# code snippet in which I have simulated my problem. In this program I have a Service function that call ReadRooms method. Now I am calling the service
Your thread action is closing over the variable i instead of its current value. You therefore have a race between the thread reading i and the increment in the for loop. You can pass it as a parameter instead:
ts[i] = new Thread(index =>
{
CallService((int)index);
});
ts[i].Start(i);
alternatively you can move the copy of temp to inside the loop instead of the thread action:
for (int i = 0; i < 4; i++)
{
int temp = i;
ts[i] = new Thread(() =>
{
CallService(temp);
});
ts[i].Start();
}
You are still 'capturing the loop variable'. You are creating a temp but too late, when i is already captured.
Try this:
for (int i = 0; i < 4; i++)
{
int temp = i; // outside the lambda
ts[i] = new Thread(() =>
{
//int temp = i; // not here
CallService(temp);
});
ts[i].Start();
}
You should put this line
int temp = i;
before the Thread creation
for (int i = 0; i < 4; i++)
{
int temp = i;
ts[i] = new Thread(() => CallService(temp));
ts[i].Start();
}
This way you will create a local copy of i that will be used by the lambda expression.