multithreading re-entrancy issue

后端 未结 3 1192
被撕碎了的回忆
被撕碎了的回忆 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:31

    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)
    
         );
     }
    

提交回复
热议问题