I\'m trying to spawn different threads for some processing. I use the for
loop index for some logic inside each thread.
How can I get the different threads to p
You are 'capturing the loop variable'. The fact that j
is used inside the lambda means the compiler will treat it differently (in essence, it will be boxed) and all thread will use the same shared variable.
The short fix:
for (int j = 1; j <= 5; j++)
{
int jCopy = j;
tasks1.Add(Task.Factory.StartNew(() =>
{
Console.WriteLine(jCopy);
}, new CancellationToken(), TaskCreationOptions.LongRunning, TaskScheduler.Default)
);
}