我正在研究如何暂停System.Timers.Timer,但我想不出在不重置计时器的情况下暂停它的正确方法。
如何暂停?
发布于 2009-10-08 11:22:49
我现在知道了,我确定它不是防弹的,所以告诉我它有什么问题……
Public Class ImprovedTimer
Inherits System.Timers.Timer
Private _sw As System.Diagnostics.Stopwatch
Private _paused As Boolean
Private _originalInterval As Double
Private _intervalRemaining As Double?
Public ReadOnly Property IntervalRemaining() As Double?
Get
Return _intervalRemaining
End Get
End Property
Public ReadOnly Property Paused() As Boolean
Get
Return _paused
End Get
End Property
Public ReadOnly Property OriginalInterval() As Double
Get
Return _originalInterval
End Get
End Property
Public Sub Pause()
If Me.Enabled Then
_intervalRemaining = Me.Interval - _sw.ElapsedMilliseconds
_paused = True
resetStopWatch(False, False)
MyBase.Stop()
End If
End Sub
Public Sub [Resume]()
If _paused Then
Me.Interval = If(_intervalRemaining.HasValue, _intervalRemaining.Value, _originalInterval)
resetStopWatch(True, False)
MyBase.Start()
End If
End Sub
Public Overloads Property Enabled() As Boolean
Get
Return MyBase.Enabled
End Get
Set(ByVal value As Boolean)
MyBase.Enabled = value
resetStopWatch(MyBase.Enabled, True)
End Set
End Property
Public Overloads Sub Start()
resetStopWatch(True, True)
MyBase.Start()
End Sub
Public Overloads Sub [Stop]()
resetStopWatch(False, True)
MyBase.Stop()
End Sub
Public Overloads Property Interval() As Double
Get
Return MyBase.Interval
End Get
Set(ByVal value As Double)
MyBase.Interval = value
If Not _paused Then
_originalInterval = MyBase.Interval
End If
End Set
End Property
Private Sub resetStopWatch(ByVal startNew As Boolean, ByVal resetPause As Boolean)
If _sw IsNot Nothing Then
_sw.Stop()
_sw = Nothing
End If
If resetPause Then
If _paused Then
Me.Interval = _originalInterval
End If
_paused = False
_intervalRemaining = Nothing
End If
If startNew Then
_sw = System.Diagnostics.Stopwatch.StartNew
End If
End Sub
Private Sub ImprovedTimer_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
resetStopWatch(False, True)
End Sub
Private Sub ImprovedTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Me.Elapsed
resetStopWatch(Me.AutoReset, True)
End Sub
End Class发布于 2009-04-14 18:59:38
没有Pause(),你可以在Pause()上写一个:
在简历()上:
如果你写了这个类,请把它贴出来作为回答,因为我们中的许多人似乎都需要Timer类之外的功能。:)
发布于 2009-04-14 19:50:48
你应该听从Shay Erlichmen给出的建议。您需要保存暂停时的剩余时间,并在计时器恢复时从该点继续。至于您当前代码的错误之处:
Me.Interval = Me.Interval - sw.ElapsedMilliseconds上面的代码将确保下一次恢复时,它将在第一个滴答器上按预期工作,但在连续的滴答器上,您将使用Me.Interval - sw.ElapsedMilliseconds作为间隔,而不是原始设置的间隔。
https://stackoverflow.com/questions/748876
复制相似问题