栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

vb.net 高精度定时器

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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#爱好者提供参考。

学习更多vb.net知识,请参看vb.net 教程 目录

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/911186.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号