共用方式為


執行緒計時器

更新:2007 年 11 月

System.Threading.Timer 類別 (Class) 對定期會在個別執行緒上執行工作而言是很有用的。例如,您可以使用執行緒計時器來檢查狀態和資料庫的完整性,或備份重要的檔案。

執行緒計時器範例

下列範例每隔兩秒便會開啟工作,並使用旗標來初始化停止計時器的 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 陳述式