关闭了循环变量在C# [英] Closing over the Loop Variable in C#

查看:129
本文介绍了关闭了循环变量在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个后,我被告知,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();
        }

不过,我的老板一直坚称其将遭受同样的问题。我用<一个href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx">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.

这篇关于关闭了循环变量在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆