Reputation: 260
I am making loop to make an array of Timers and give each timer a function
here's something like what i did:
dim timer(10) as Timer
for i = 0 to 5
timer(i) = new Timer
AddHandler timer(i).Tick, Function(senderX, eX) timerFunction(i)
next
i have this function:
Private Function timerFunction(ByVal timerNo As Integer)
MsgBox(timerNo)
End Function
but i am getting 6
as the value of timerNo
for every timer
i call with this:
timer(3).Start()
i outputs 6
even in i change the parameter to a number from 1
to 5
why is it diong that?
Upvotes: 0
Views: 486
Reputation: 5393
You have "closed over the loop variable". The value of timerNo
is evaluated at the time the function is called which is always after the loop has completed, so the value of timerNo
will always be 6.
You should have got a compiler warning: "BC42324 Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.
"
To do this with your example...
Dim timer(10) As Timer
For i As Integer = 0 To 5
Dim j As Integer = i
timer(i) = New Timer
timer(i).Interval = 1000
timer(i).Enabled = True
AddHandler timer(i).Tick, Function(senderX, eX) timerFunction(j)
Next
Function timerFunction(timerNo As Integer) As String
MsgBox(timerNo)
Return timerNo.ToString
End Function
This way, a new instance of j
is created for each iteration of the loop.
Upvotes: 1