I have a problem with the Timer class in that there is a chance that a timer would fire right before you call Dispose() since you will probably call Dispose() from some other thread. You may have something like:
Public Sub TimerTick() Handles itsTimer.Elapsed
Do Something
End Sub
And then from somewhere else in the code, when your app is done, you call
itsTimer.Dispose()
The only way I can think of doing this is:
Public Sub SomeMethod()
SyncLock(itsTimer.SynchronizingObject)
itsTimer.Dispose()
End SyncLock
ENd Sub
This is not a great thing to do esp. since I am holding a lock on an object I am disposing. I can create my own lock and syncLock on that but is there a simple way?
Locking the
SynchronizingObjectwill not prevent the race condition. Neither will unregistering the tick event. In both cases, it’s possible to have an event run after the timer is disposed.You’d need to define a piece of shared state outside the timer that is explicitly checked at the beginning of your timer event handler. I call this an asynchronous callback context.