Closing a Loop variable in C #

From this publication, I was told that the next section of code suffers from the “egregious act of closing over a loop variable”.

foreach (Canidate canidate in allCanidates) { Thread newThread = new Thread(delegate() { BusyWait(canidate); }); newThread.Start(); } 

I switched it to this:

 foreach (Canidate canidate in allCanidates) { var can = canidate; Thread newThread = new Thread(delegate() { BusyWait(can); }); newThread.Start(); } 

But my boss continues to insist that he will suffer from the same problems. I used this link to try to solve this problem. Can someone help me solve the problem correctly so that my code runs correctly. This question is all new to me, and I'm not sure I fully understand it.

+6
source share
1 answer

Closing variables that subsequently change values ​​causes a problem.

  • candidate changes each circle around the loop and causes problems.
  • can re-create each "circle" around the loop, never changes and does not cause problems.
+4
source

Source: https://habr.com/ru/post/910287/


All Articles