我想创建一个可以暂停和恢复的计时器对象。
当前Timers.Timer
类的问题在于,当您调用Stop()
然后调用Start()
时,它会重置间隔并在整个间隔过去后再次触发。
例如,如果我有timerA
timerA.Interval = 5000
现在如果我做timerA.Start()
然后3秒后我打电话给timerA.Stop()
然后我想等2分钟。
在这2分钟之后,我想打电话给timerA.Start()
,这应该在 2秒之后触发Elapsed事件(即恢复我2分钟前离开的地方)。但问题是Timers.Timer.Start()
将在5秒后再次发射(从0开始,而不是从3秒开始)。
无论如何,我创建了一个继承自Timers.Timer
的VB.NET类,所以如果上面的暂停逻辑与我的代码一致,请你告诉我们吗?
代码:
Imports System.Timers
Public Class TimerWithPause
Inherits Timers.Timer
Dim m_stopwatch As New Stopwatch
Dim m_interval As Integer 'original interval
Dim m_remainngtime As Integer 'to use when the Pause is requested
Dim m_state As TimerState = TimerState.Stopped
Public Sub New(Interval As Integer)
m_interval = Interval
MyBase.Interval = Interval
End Sub
Public Overloads Property Interval As Integer
Get
Return m_interval
End Get
Set(value As Integer)
m_interval = value
MyBase.Interval = m_interval
End Set
End Property
ReadOnly Property CurrentState As TimerState
Get
Return m_state
End Get
End Property
Public Overloads Sub Start(startSate As StartStatus)
MyBase.Interval = m_interval
Select Case startSate
Case StartStatus.StartNew
StartNew()
Case StartStatus.ResumeTimer
'if current state is paused then resume
If m_state = TimerState.Paused Then
m_state = TimerState.Running
m_stopwatch.Start()
If m_remainngtime > 0 Then
MyBase.Interval = m_remainngtime
End If
MyBase.Start()
ElseIf m_state = TimerState.Stopped Then 'else if the timer is stopped then start new
StartNew()
End If
End Select
End Sub
Public Overloads Sub [Stop](stopState As StopStatus)
Select Case stopState
Case StopStatus.StopTimer
m_state = TimerState.Stopped
m_stopwatch.Reset()
MyBase.Stop()
Case StopStatus.PauseTimer
m_state = TimerState.Paused
m_stopwatch.Stop()
MyBase.Stop()
m_remainngtime = m_interval - m_stopwatch.ElapsedMilliseconds
End Select
End Sub
Private Sub TimerWithPause_Elapsed(sender As Object, e As ElapsedEventArgs) Handles Me.Elapsed
StartNew() 'if the timer fires then it starts new cycle (because pauses happen in a middle of a running cycle)
End Sub
Private Sub StartNew()
m_remainngtime = 0
MyBase.Interval = m_interval
m_state = TimerState.Running
m_stopwatch.Restart()
MyBase.Start()
End Sub
Enum StartStatus
StartNew = 1
ResumeTimer = 2
End Enum
Enum StopStatus
PauseTimer = 1
StopTimer = 3
End Enum
Enum TimerState
Running = 1
Stopped = 2
Paused = 3
End Enum
End Class
我用这种方式:
Dim WithEvents tmr As New TimerWithPause(8000)
Private Sub RadButton10_Click(sender As Object, e As EventArgs) Handles RadButton10.Click
Select Case tmr.CurrentState
Case TimerWithPause.TimerState.Running
tmr.Stop(TimerWithPause.StopStatus.PauseTimer)
Case TimerWithPause.TimerState.Stopped
tmr.Start(TimerWithPause.StartStatus.StartNew)
Case TimerWithPause.TimerState.Paused
tmr.Start(TimerWithPause.StartStatus.ResumeTimer)
End Select
End Sub
提前谢谢你们