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

查看:9
本文介绍了关闭 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();
    }

我把它改成这样:

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

            newThread.Start();
        }

但我的老板一直坚持认为它会遇到同样的问题.我使用了 this 链接以尝试解决此问题.有人可以帮助我正确解决问题,以便我的代码正确执行.这个问题对我来说是全新的,我不确定我是否完全理解它.

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 在循环中的每一个圈"都会改变,导致问题.
  • can 是围绕循环的每一圈"新创建的,永远不会改变,并且不会导致问题.
  • 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天全站免登陆