I have a windows forms timer with an async callback that await a database operation, why the await is executed again even before the previous callback has not finished yet? How can I fix this? Many people say that System.Windows.Forms.Timer wait that previous callback operation finishes before executing new one.
Private Async Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' I have an array with 6 elements that i control
' for executing database operation
For i=1 To 6
If(some condition is true in array index)
Await SaveAsync()
'set to false the condition in array index after save
End If
Next
End Sub
Thanks in advance.
CodePudding user response:
It is presumably because the asynchronous call takes longer than the Interval
of your Timer
. That would mean the Tick
event would be raised again before the previous event handler has finished executing. If what you want is a specific interval between when the previous call has completed and the next event then you should stop the Timer
, make the call and then start it again:
Private Async Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
Await SaveAsync()
Timer1.Start()
End Sub