0

This is a cumbersome behaviour when creating several task in a for loop:

Private Sub DoSomeTasks()
    For i = 1 to 3
       Dim oTest as cTest = New cTest
       Dim oTask As Task = Task.Factory.StartNew(Sub() oTest.DoSimulation(i))
    Next
End Sub

This code will create all tasks with the same i value (= 3). Anyone has experienced something similar? Anyone has a clue on how to solve it?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Winigu
  • 1
  • 3
  • 2
    Make a variable inside your `For` loop that equals `i` and use that instead of `i`. https://stackoverflow.com/questions/227820/why-is-it-bad-to-use-an-iteration-variable-in-a-lambda-expression – gunr2171 Nov 03 '17 at 17:30
  • There's probably a compiler warning you missed which told you what to do. – djv Nov 03 '17 at 18:47

0 Answers0