Stephen Pefanis Stephen Pefanis - 2 months ago 15x Question

Multiple Threads within application

I am working on an application and I would like to create multiple timers that all fire at different intervals. On each fire I would like them to call a relevant function.

Initially, I would like a timer that fire every 100ms, 1 second, 10 second, 30second ect.
On each "tick" I would like to call a function that reads data from a device and stores it in a buffer.

What is the best way to create the required timers and handle their events?

I have done something similar to this for each timer, but it's cumbersome, so looking for something simpler/smarter.


Dim Timer100msUpdateInterval As DateInterval = 100
Dim Timer100msUpdate As Threading.Timer

'On Load
Dim TimerCallBack100ms As Threading.TimerCallback = New Threading.TimerCallback(AddressOf Timer100msUpdateTimerEvent)
Timer100msUpdate = New Threading.Timer(TimerCallBack100ms, Nothing, 100, Timer100msUpdateInterval)

'For each timer
Private Sub Timer100msUpdateTimerEvent(ByVal state As Object)
End Sub

I like the concept approach by @kiLLua, but need some way to identify when each timer fires, which timer ran

    Dim timers As New List(Of System.Threading.Timer)
    timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 100, 100))
    timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 1000, 1000))
    timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 10000, 10000))
    timers.Add(New System.Threading.Timer(AddressOf MyHandler, Nothing, 30000, 30000))

where handler is defined as.

Sub MyHandler(state As Object)

End Sub

If your device cannot have 2 simultaneous requests then you'll need to implement some locking in MyHandler.

timers.Add(New System.Threading.Timer(AddressOf MyHandler, myDataRow, 30000, 30000))

Sub MyHandler(state As Object)
     dim row = CType(state, DataRow)
End Sub