Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
It's not the thread's fault, it's the closures .
When you refer to a variable in a lambda, it is accessed by reference.
So it turned out that at the time of launch, the value of i is already 2. You
can solve this problem if you copy the value of i into a new variable like this:
for (int i = 0; i < 2; i++)
{
var i2 = i;
Thread thread = new Thread(() =>
{
Console.WriteLine("main index: " + i2);
});
thread.Start();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question