我有一个使用
System.Windows.Forms.Timer
的应用程序,并且发现计时器间隔存在问题。 当我在 180 秒的持续时间内使用 1000 的间隔时,经过的时间始终约为 183 秒。 当我使用 995 的间隔时,经过的时间是准确的(即 180 秒)。 我在 3 台不同的电脑上尝试过,每台电脑的结果都相同。 下面的代码使用 2 个文本框来显示开始和结束时间,并使用一个标签作为倒计时器。
任何人都可以解释这种行为吗?
Public Class Form1
Private WithEvents tmr As New System.Windows.Forms.Timer
Private Duration As Integer = 180
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RunTimer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblActivityTimer.Text = FormatCounter(Duration)
tmr.Interval = 1000
End Sub
Private Sub RunTimer()
tmr.Start()
TextBox1.Text = Now.ToString()
End Sub
Private Function FormatCounter(sec As Integer) As String
Dim Hours, Minutes, Seconds As Integer
Hours = sec \ 3600
Seconds = sec Mod 3600
Minutes = Seconds \ 60
Seconds = sec Mod 60
FormatCounter = Hours.ToString.PadLeft(2, "0"c) & ":" _
& Minutes.ToString.PadLeft(2, "0"c) _
& ":" _
& Seconds.ToString.PadLeft(2, "0"c)
End Function
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
Duration -= 1
lblActivityTimer.Text = FormatCounter(Duration)
If Duration = 0 Then
TextBox2.Text = Now.ToString()
tmr.Stop()
End If
End Sub
End Class
要小心一些事情。
在设计时您设置了 FrameDelay:
tmr.FrameDelay = 100;
然后在运行时设置Interval不起作用:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblActivityTimer.Text = FormatCounter(Duration)
tmr.Interval = 1000
End Sub
ps 使用秒表,它提供了一组方法和属性,您可以使用它们来准确测量经过的时间。
Shared Sub Main(ByVal args() As String)
Dim stopWatch As New Stopwatch()
stopWatch.Start()
Thread.Sleep(10000)
stopWatch.Stop()
' Get the elapsed time as a TimeSpan value.
Dim ts As TimeSpan = stopWatch.Elapsed
' Format and display the TimeSpan value.
Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
Console.WriteLine( "RunTime " + elapsedTime)
End Sub 'Main