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 print 1,2,3,4, 5 in the code below? Each time I run this, I get different numbers as output - 3,3,3,4,6,6 & 2,2,3,5,5,6 etc.
I tried using the lock object, but it stil wasn't doing it correctly. Can anyone help me achive this. I just want to make sure each thread/task gets the right index. Note that each task has been forced to run on a separate thread.
List<Task> tasks1 = new List<Task>();
for (int j = 1; j <= 5; j++)
{
tasks1.Add(Task.Factory.StartNew(() =>
{
Console.WriteLine(j);
}
, new CancellationToken()
, TaskCreationOptions.LongRunning
, TaskScheduler.Default)
);
}
Task.WaitAll(tasks1.ToArray());
Console.Read();