array of threads c#
All of the threads are printing the same variable.
Your lambda expression (() => c1.k(i)
) captures the i
variable by reference.
Therefore, when the lambda expression runs after i++
, it picks up the new value of i
.
To fix this, you need to declare a separate variable inside the loop so that each lambda gets its own variable, like this:
for (int i = 0; i < 4; i++)
{
int localNum = i;
threadsArray[i] = new Thread(() => c1.k(localNum));
}
You are closing over the i variable.
Try this instead
for (int i = 0; i < 4; i++)
{
int x = i;
threadsArray[i] = new Thread(() => c1.k(x));
}