Condividi tramite


Timer di thread

Aggiornamento: novembre 2007

La classe System.Threading.Timer risulta utile per l'esecuzione periodica di un'attività su un thread distinto. È ad esempio possibile utilizzare un timer di thread per verificare lo stato e l'integrità di un database o per il backup di file critici.

Esempio di timer di thread

Nell'esempio seguente viene avviata un'attività ogni due secondi e un flag viene utilizzato per inizializzare il metodo Dispose, che consente l'arresto del timer. Lo stato viene quindi inserito nella finestra di output. Si consiglia di visualizzare tale finestra premendo CTRL+ALT+O prima di testare il codice.

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

I timer di thread risultano particolarmente utili quando l'oggetto System.Windows.Forms.Timer non è disponibile, ad esempio quando si sviluppano applicazioni console.

Vedere anche

Concetti

Multithreading avanzato con Visual Basic

Applicazioni multithread

Riferimenti

System.Threading

Istruzione SyncLock