VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > VB.net教程 >
  • vb.net 高精度定时器

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
在vb.net下常用的计时器非组件中的Timer莫属,但是实际应用的时候大家会发现一个比较大的问题,精度不够。
我写了个代码来测试timer的精度,间隔时间设置为1毫秒,具体代码如下:
 
 
    Dim counter1 As Integer
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Timer1.Enabled = True Then
            Timer1.Stop()
        Else
            Timer1.Start()
        End If
    End Sub
 
 
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        counter1 += Timer1.Interval
        TextBox1.Text = counter1
    End Sub
 
 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        counter1 = 0
        Timer1.Interval = 1
    End Sub
结果对比手机时间,实测得到计时次数为 38360,确实相差比较大。
因此我考虑了如下代码:
 
Public Class CustomTimer
    Public Property Interval As Integer
    Public Event Tick()
    Public Property Enabled As Boolean
    Sub New()
        Me.Interval = 100
        Me.Enabled = False
    End Sub
 
    Sub New(ByVal Interval As Integer)
        Me.Interval = Interval
        Me.Enabled = False
    End Sub
 
    Public Sub Start()
        Me.Enabled = True
        Dim th As New Threading.Thread(AddressOf count)
        th.Priority = Threading.ThreadPriority.Highest
        th.Start()
    End Sub
 
    Private Sub count()
        Do While Me.Enabled = True
            Threading.Thread.Sleep(Interval)
            RaiseEvent Tick()
        Loop
    End Sub
 
    Public Sub [Stop]()
        Me.Enabled = False
    End Sub
End Class
窗体调用代码:
 
 
    Dim counter1 As Integer
    Dim counter2 As Integer
 
    Dim ct As CustomTimer
 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.CheckForIllegalCrossThreadCalls = False
        counter1 = 0
        counter2 = 0
        Timer1.Interval = 1
 
        ct = New CustomTimer(1)
        AddHandler ct.Tick, AddressOf CustomTimer_Tick
    End Sub
 
    Private Sub CustomTimer_Tick()
        counter2 += ct.Interval
        TextBox2.Text = counter2
    End Sub
 
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If ct.Enabled = True Then
            ct.Stop()
        Else
            ct.Start()
        End If
    End Sub
经过测试,手机秒表时间 1'00.23 ,程序计数次数:57676
 
也就是60230对应57676,比系统Timer精度要高。
 
 
 
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
————————————————
版权声明:本文为CSDN博主「VB.Net」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/UruseiBest/article/details/111305358

相关教程