线程计时器

更新:2007 年 11 月

System.Threading.Timer 类可用于定期在单独的线程上运行任务。例如,可以使用线程计时器来检查数据库的状态和完整性,或备份重要文件。

线程计时器示例

下面的示例每两秒启动一项任务,并使用一个标志来启动停止该计时器的 Dispose 方法。此示例将状态显示到输出窗口上,因此在测试代码前,应按下 Ctrl+Alt+O 显示该窗口。

Class StateObjClass
    ' Used to hold parameters for calls to TimerTask
    Public SomeValue As Integer
    Public TimerReference As System.Threading.Timer
    Public TimerCanceled As Boolean
End Class

Sub RunTimer()
    Dim StateObj As New StateObjClass
    StateObj.TimerCanceled = False
    StateObj.SomeValue = 1
    Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
    ' Create a timer that calls a procedure every 2 seconds.
    ' Note: There is no Start method; the timer starts running as soon as 
    ' the instance is created.
    Dim TimerItem As New System.Threading.Timer(TimerDelegate, StateObj, _
                                                2000, 2000)
    StateObj.TimerReference = TimerItem  ' Save a reference for Dispose.

    While StateObj.SomeValue < 10 ' Run for ten loops.
        System.Threading.Thread.Sleep(1000)  ' Wait one second.
    End While

    StateObj.TimerCanceled = True  ' Request Dispose of the timer object.
End Sub

Sub TimerTask(ByVal StateObj As Object)
    Dim State As StateObjClass = CType(StateObj, StateObjClass)
    ' Use the interlocked class to increment the counter variable.
    System.Threading.Interlocked.Increment(State.SomeValue)
    System.Diagnostics.Debug.WriteLine("Launched new thread  " & Now)
    If State.TimerCanceled Then    ' Dispose Requested.
        State.TimerReference.Dispose()
        System.Diagnostics.Debug.WriteLine("Done  " & Now)
    End If
End Sub

System.Windows.Forms.Timer 对象不可用时(例如在开发控制台应用程序时),线程计时器特别有用。

请参见

概念

高级多线程处理 (Visual Basic)

多线程应用程序

参考

System.Threading

SyncLock 语句