Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing over the Loop Variable in C#

From this post, I was told that the following section of code suffered from "the egregious act of closing over the 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 keeps insisting that it will suffer from the same issues. I used this link to try to solve this issue. Can someone help me to correctly solve the issue so that my code will execute correctly. this issue is all new to me, and I am not sure I full understand it.

like image 451
user489041 Avatar asked Mar 08 '12 22:03

user489041


1 Answers

Closing over variables that later change values is what is causing the problem.

  • candidate changes every "lap" around the loop and will cause problems.
  • can is newly created every "lap" around the loop, never changes, and won't cause problems.
like image 125
Joachim Isaksson Avatar answered Sep 30 '22 06:09

Joachim Isaksson