Just to complete the other answers. In C# 5.0 (.NET 4.5) there was a breaking change in relation to closing over foreach
loop variable, but not to closure over for
loop variable.
See details (and preface Update note) in Eric Lippert. Closing over the loop variable considered harmful and his Closing over the loop variable, part two
Note that this issue is independent on multithreading or TPL (Task Parallel Library) usage.
The other answers and comments mentioned that it was discussed before but there was no linking to any of the previous answers. Here are some, for the sake of inter-linking:
- Access to Modified Closure
- Access to Modified Closure (2)
- C# Captured Variable In Loop
- ReSharper Warning - Access to Modified Closure
- modified closure warning in ReSharper
- From Eric Lippert's blog: “don't close over the loop variable” [duplicate]
- Why is it bad to use an iteration variable in a lambda expression
- How do I get around this lambda expression outer variable issue?
- Strange behavior when using lambda expression on WPF buttons click event
- C# - The foreach identifier and closures
- How to tell a lambda function to capture a copy instead of a reference in C#?
- Why do I get: “iteration variable in a lambda expression may have unexpected results” [duplicate]
- Does this code really cause an “access to modified closure” problem?
- Why is it bad to use an iteration variable in a lambda expression
- How to suppress VB's “Iteration variable shouldn't been used in lambda expression”
- Run multiply instances of the same method simultaneously in c# without data loss?
- What are the correct semantics of a closure over a loop variable? [closed]
- C# under the hood code generation for lambdas within loops
- What is the correct way to dynamically add an undetermined number of clauses to a Linq 2 Sql query?
- etc.