0

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?

2
  • timerFunction's value of timerNo is calculated at the time the function is called, not when you do the AddHandler. See ericlippert.com/2009/11/12/… Commented Jul 26, 2017 at 3:36
  • 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." Commented Jul 26, 2017 at 3:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I already have the solution by using Dim index As Integer = Array.IndexOf(timer, CType(sender2, System.Windows.Forms.Timer)) but thank you really for this.. I'll look around it and maybe use it. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.