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
Answered millions of times. it is related with closure. Change your code as below
for (int j = 1; j <= 5; j++)
{
int temp = j;
tasks1.Add(Task.Factory.StartNew(() =>
{
Console.WriteLine(temp);
}, new CancellationToken(), TaskCreationOptions.LongRunning, TaskScheduler.Default)
);
}
I would recomment to read this: Loop variables and Closures