看来我++中的循环迭代结束前被执行一次。为什么我得到IndexOutOfRangeException?
It seems that i++ gets executed one more time before the loop iteration is finished. Why do I get the IndexOutOfRangeException?
推荐答案您正在关闭了循环变量。当它的时候了 WorkerMethod 来被调用, I 可以有两个值,0或1不是值
You are closing over loop variable. When it's time for WorkerMethod to get called, i can have the value of two, not the value of 0 or 1.
当您使用闭包要明白,你没有使用该变量的那一刻,你用变量本身的价值是很重要的。所以,如果你创建循环lambda表达式,像这样:
When you use closures it's important to understand that you are not using the value that the variable has at the moment, you use the variable itself. So if you create lambdas in loop like so:
for(int i = 0; i < 2; i++) { actions[i] = () => { Console.WriteLine(i) }; }和后来执行的行动,他们都将打印2,因为这是什么样的价值 I 是目前
and later execute the actions, they all will print "2", because that's what the value of i is at the moment.
在介绍循环中的局部变量将解决你的问题:
Introducing a local variable inside the loop will solve your problem:
for (int i = 0; i < 2; i++) { int index = i; Task.Factory.StartNew(() => WorkerMethod(arr[index])); }
< ReSharper的即插即用GT; 这是一个原因尝试 ReSharper的 - 它给了很多帮助您捕捉这样一个早期的错误警告。 关闭了一个循环变量是他们当中的< / ReSharper的插件>
<Resharper plug> That's one more reason to try Resharper - it gives a lot of warnings that help you catch the bugs like this one early. "Closing over a loop variable" is amongst them </Resharper plug>
更多推荐
For循环超出范围
发布评论