multithreading re-entrancy issue

后端 未结 3 1124
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 19:26

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

3条回答
  •  情歌与酒
    2021-01-27 20:17

    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

提交回复
热议问题