关闭了循环变量在C#变量、关闭了

2023-09-02 01:59:15 作者:没有公主命要有女王心。

从这个后,我被告知,code以下部分遭受从关闭了循环变量的恶劣行为。

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

不过,我的老板一直坚称其将遭受同样的问题。我用this链接来尝试解决这个问题。有人可以帮助我正确地解决这个问题,使我的code能够正确执行。这个问题是所有新的给我,我不知道我完全理解这一点。

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.

推荐答案

关闭了变数,后来更改值是什么原因造成的问题。

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.