Winforms计时器不准确

时间:2016-11-15 17:18:08

标签: vb.net winforms timer

我有一个使用System.Windows.Forms.Timer的应用,并且看到了定时器间隔的问题。当我使用1000的间隔持续180秒时,经过的时间始终为183秒左右。当我使用995的间隔时,经过的时间是准确的(即180秒)。我在3台不同的PC上尝试了这一点,每台PC上都有相同的结果。下面的代码使用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

2 个答案:

答案 0 :(得分:0)

使用Stop Watch,它提供了一组方法和属性,可用于准确测量已用时间。

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

答案 1 :(得分:-1)

有两种随时可用的Timer对象替代方案:

  • System.Threading.Timer(解释here,我的第一个选择)
  • System.Timers.Timer(解释here