A lambda that uses an external variable actually captures the variable, not the value stored in it. This means that as the loop continues, the value you read from the captured variable will change.
You can fix this using the temp variable inside the loop. Your code will be much cleaner if you used async/await instead of ContinueWith and lambdas, for example:
for (int i=0;i<N;i++) {
In general, you can avoid capture problems by copying the loop variable to the variable defined inside the loop area.
This fixes the problem since a temporary variable exists only inside the loop body. A lambda is also created inside the loop body and captures a local immutable variable:
for (int i=0;i<N;i++) { var temp=i; var myLambda = new Action(()=>MyMethod(temp));
Even better, to avoid capture and pass the loop value as a ContinueWith state parameter, for example:
for (int i = 0; i < N; ++i) { //... var task = anotherTask.ContinueWith( (t,state) => ProcessResult((int)state, t.Result), i); //... }
source share