I have a custom class written, which I instantiate from an event procedure similar to
Private Sub EventHandler
For intForCounter = 1 to intUserEntry
Dim newObj As New MyClass
newObj.Property
newObj.Method()
Next
End Sub
The class itself looks something like this
Public Property Time As Date
'First attempt:
Dim tmeExec As New Timer
Public Sub Method()
'Second Attempt
Dim tmeExec As New Timer
'A bunch of code for converting a timespan to milliseconds and storing that in intInterval
With tmeExec
.Enabled = True
.Interval = intInterval
End With
AddHandler tmeExec.Tick, AddressOf TickHandler
End Sub
Private Sub TickHandler(ByVal myObj As Object, ByVal myArgs As EventArgs)
Dim tmeSender As Timer = CType(myObj, Timer)
tmeSender.Stop()
'Some code here to do something
End Sub
When I had the time placement in the location ‘First Attempt’, everything fired at the last interval specified.
My expectation is that each time a new object is instantiated, a new timer would have been instantiated with it, and so putting the instantiation in the class would be the right way to go. That’s not the case.
But I want to know why it behaves as it does. It’s fine to know HOW something works, but if you know WHY something works, you don’t make that goof again. I asked my professor, but didn’t really understand his answer as fully as I’d like to.
If you place the instantiation of the Timer outside the Method (at ‘First attempt’), then you only have a single timer. Each time you call Method(), you are just setting the properties of the existing timer and adding a new event handler to the existing timer.
By moving the Timer instantiation into the Method(), then each time Method() is called, a new Timer object is created.