Condividi tramite


Timer Classe

Definizione

Fornisce un meccanismo per l'esecuzione di un metodo in un thread del pool di thread a intervalli specificati. Questa classe non può essere ereditata.

public ref class Timer sealed : IDisposable
public ref class Timer sealed : MarshalByRefObject, IAsyncDisposable, IDisposable
public ref class Timer sealed : MarshalByRefObject, System::Threading::ITimer
public ref class Timer sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : IDisposable
public sealed class Timer : MarshalByRefObject, IAsyncDisposable, IDisposable
public sealed class Timer : MarshalByRefObject, System.Threading.ITimer
public sealed class Timer : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
type Timer = class
    inherit MarshalByRefObject
    interface IAsyncDisposable
    interface IDisposable
    interface ITimer
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type Timer = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class Timer
Implements IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IAsyncDisposable, IDisposable
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements ITimer
Public NotInheritable Class Timer
Inherits MarshalByRefObject
Implements IDisposable
Ereditarietà
Timer
Ereditarietà
Attributi
Implementazioni

Esempio

Nell'esempio seguente viene definita una classe StatusChecker che include un metodo CheckStatus la cui firma corrisponde al delegato TimerCallback. L'argomento state del metodo CheckStatus è un oggetto AutoResetEvent utilizzato per sincronizzare il thread dell'applicazione e il thread del pool di thread che esegue il delegato di callback. La classe StatusChecker include anche due variabili di stato:

invokeCount Indica il numero di chiamate al metodo di callback.

maxCount Determina il numero massimo di chiamate al metodo di callback.

Il thread applicazione crea il timer, che attende un secondo e quindi esegue il metodo di callback CheckStatus ogni 250 millisecondi. Il thread dell'applicazione si blocca quindi fino a quando non viene segnalato l'oggetto AutoResetEvent. Quando il metodo di callback CheckStatus viene eseguito maxCount volte, chiama il metodo AutoResetEvent.Set per impostare lo stato dell'oggetto AutoResetEvent su segnalato. La prima volta che si verifica questo problema, il thread dell'applicazione chiama il metodo Change(Int32, Int32) in modo che il metodo di callback venga eseguito ogni metà del secondo. Si blocca nuovamente fino a quando non viene segnalato l'oggetto AutoResetEvent. In questo caso, il timer viene eliminato definitivamente chiamando il relativo metodo Dispose e l'applicazione termina.

using namespace System;
using namespace System::Threading;

ref class StatusChecker
{
private:
    int invokeCount, maxCount;

public:
    StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    void CheckStatus(Object^ stateInfo)
    {
        AutoResetEvent^ autoEvent = dynamic_cast<AutoResetEvent^>(stateInfo);
        Console::WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.",
                           DateTime::Now, ++invokeCount);

        if (invokeCount == maxCount) {
            // Reset the counter and signal the waiting thread.
            invokeCount  = 0;
            autoEvent->Set();
        }
    }
};

ref class TimerExample
{
public:
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        AutoResetEvent^ autoEvent = gcnew AutoResetEvent(false);

        StatusChecker^ statusChecker = gcnew StatusChecker(10);

        // Create a delegate that invokes methods for the timer.
        TimerCallback^ tcb =
           gcnew TimerCallback(statusChecker, &StatusChecker::CheckStatus);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console::WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
                           DateTime::Now);
        Timer^ stateTimer = gcnew Timer(tcb, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent->WaitOne(5000, false);
        stateTimer->Change(0, 500);
        Console::WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent->WaitOne(5000, false);
        stateTimer->~Timer();
        Console::WriteLine("\nDestroying timer.");
    }
};

int main()
{
    TimerExample::Main();
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        // Create an AutoResetEvent to signal the timeout threshold in the
        // timer callback has been reached.
        var autoEvent = new AutoResetEvent(false);
        
        var statusChecker = new StatusChecker(10);

        // Create a timer that invokes CheckStatus after one second, 
        // and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", 
                          DateTime.Now);
        var stateTimer = new Timer(statusChecker.CheckStatus, 
                                   autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne();
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period to .5 seconds.\n");

        // When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne();
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    private int invokeCount;
    private int  maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal the waiting thread.
            invokeCount = 0;
            autoEvent.Set();
        }
    }
}
// The example displays output like the following:
//       11:59:54.202 Creating timer.
//       
//       11:59:55.217 Checking status  1.
//       11:59:55.466 Checking status  2.
//       11:59:55.716 Checking status  3.
//       11:59:55.968 Checking status  4.
//       11:59:56.218 Checking status  5.
//       11:59:56.470 Checking status  6.
//       11:59:56.722 Checking status  7.
//       11:59:56.972 Checking status  8.
//       11:59:57.223 Checking status  9.
//       11:59:57.473 Checking status 10.
//       
//       Changing period to .5 seconds.
//       
//       11:59:57.474 Checking status  1.
//       11:59:57.976 Checking status  2.
//       11:59:58.476 Checking status  3.
//       11:59:58.977 Checking status  4.
//       11:59:59.477 Checking status  5.
//       11:59:59.977 Checking status  6.
//       12:00:00.478 Checking status  7.
//       12:00:00.980 Checking status  8.
//       12:00:01.481 Checking status  9.
//       12:00:01.981 Checking status 10.
//       
//       Destroying timer.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Use an AutoResetEvent to signal the timeout threshold in the
        ' timer callback has been reached.
        Dim autoEvent As New AutoResetEvent(False)

        Dim statusChecker As New StatusChecker(10)

        ' Create a timer that invokes CheckStatus after one second, 
        ' and every 1/4 second thereafter.
        Console.WriteLine("{0:h:mm:ss.fff} Creating timer." & vbCrLf, 
                          DateTime.Now)
        Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus, 
                                    autoEvent, 1000, 250)

        ' When autoEvent signals, change the period to every half second.
        autoEvent.WaitOne()
        stateTimer.Change(0, 500)
        Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)

        ' When autoEvent signals the second time, dispose of the timer.
        autoEvent.WaitOne()
        stateTimer.Dispose()
        Console.WriteLine(vbCrLf & "Destroying timer.")
    End Sub
End Module

Public Class StatusChecker
    Dim invokeCount, maxCount As Integer 

    Sub New(count As Integer)
        invokeCount  = 0
        maxCount = count
    End Sub

    ' The timer callback method.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.", 
                          DateTime.Now, invokeCount)
        If invokeCount = maxCount Then
            ' Reset the counter and signal the waiting thread.
            invokeCount = 0
            autoEvent.Set()
        End If
    End Sub
End Class
' The example displays output like the following:
'       11:59:54.202 Creating timer.
'       
'       11:59:55.217 Checking status  1.
'       11:59:55.466 Checking status  2.
'       11:59:55.716 Checking status  3.
'       11:59:55.968 Checking status  4.
'       11:59:56.218 Checking status  5.
'       11:59:56.470 Checking status  6.
'       11:59:56.722 Checking status  7.
'       11:59:56.972 Checking status  8.
'       11:59:57.223 Checking status  9.
'       11:59:57.473 Checking status 10.
'       
'       Changing period to .5 seconds.
'       
'       11:59:57.474 Checking status  1.
'       11:59:57.976 Checking status  2.
'       11:59:58.476 Checking status  3.
'       11:59:58.977 Checking status  4.
'       11:59:59.477 Checking status  5.
'       11:59:59.977 Checking status  6.
'       12:00:00.478 Checking status  7.
'       12:00:00.980 Checking status  8.
'       12:00:01.481 Checking status  9.
'       12:00:01.981 Checking status 10.
'       
'       Destroying timer.

Commenti

Usare un delegato TimerCallback per specificare il metodo da eseguire Timer. La firma del delegato TimerCallback è:

void TimerCallback(Object state)
void TimerCallback(Object state)
Sub TimerCallback(state As Object)

Il delegato timer viene specificato quando viene costruito il timer e non può essere modificato. Il metodo non viene eseguito sul thread che ha creato il timer; viene eseguito su un thread ThreadPool fornito dal sistema.

Mancia

.NET include diverse classi timer, ognuna delle quali offre funzionalità diverse:

  • System.Timers.Timer, che genera un evento ed esegue il codice in uno o più sink di eventi a intervalli regolari. La classe è destinata all'uso come componente basato su server o di servizio in un ambiente multithreading; non ha un'interfaccia utente e non è visibile in fase di esecuzione.
  • System.Threading.Timer, che esegue un singolo metodo di callback su un thread del pool di thread a intervalli regolari. Il metodo di callback viene definito quando viene creata un'istanza del timer e non può essere modificato. Analogamente alla classe System.Timers.Timer, questa classe è destinata all'uso come componente basato su server o servizio in un ambiente multithreading; non ha un'interfaccia utente e non è visibile in fase di esecuzione.
  • System.Windows.Forms.Timer, un componente Windows Form che genera un evento ed esegue il codice in uno o più sink di eventi a intervalli regolari. Il componente non ha interfaccia utente ed è progettato per l'uso in un ambiente a thread singolo; viene eseguito nel thread dell'interfaccia utente.
  • System.Web.UI.Timer (solo .NET Framework), un componente ASP.NET che esegue postback di pagine Web asincrone o sincrone a intervalli regolari.
  • System.Windows.Threading.DispatcherTimer, un timer integrato nella coda di Dispatcher. Questo timer viene elaborato con una priorità specificata a un intervallo di tempo specificato.

Quando si crea un timer, è possibile specificare una quantità di tempo di attesa prima della prima esecuzione del metodo (tempo di scadenza) e un intervallo di tempo di attesa tra le esecuzioni successive (periodo). La classe Timer ha la stessa risoluzione dell'orologio di sistema. Ciò significa che se il periodo è minore della risoluzione del clock di sistema, il delegato TimerCallback verrà eseguito a intervalli definiti dalla risoluzione dell'orologio di sistema, che è circa 15 millisecondi nei sistemi Windows 7 e Windows 8. È possibile modificare il tempo di scadenza e il periodo oppure disabilitare il timer usando il metodo Change.

Nota

Finché si usa un Timer, è necessario mantenere un riferimento a esso. Come per qualsiasi oggetto gestito, un Timer è soggetto a Garbage Collection quando non vi sono riferimenti. Il fatto che un Timer sia ancora attivo non impedisce la raccolta.

Nota

L'orologio di sistema utilizzato è lo stesso orologio usato da GetTickCount, che non è interessato dalle modifiche apportate con timeBeginPeriod e timeEndPeriod.

Quando un timer non è più necessario, usare il metodo Dispose per liberare le risorse mantenute dal timer. Si noti che i callback possono verificarsi dopo che è stato chiamato l'overload del metodo Dispose(), perché il timer accoda i callback per l'esecuzione dai thread del pool di thread. È possibile utilizzare l'overload del metodo Dispose(WaitHandle) per attendere il completamento di tutti i callback.

Il metodo di callback eseguito dal timer deve essere reentrant, perché viene chiamato su ThreadPool thread. Il callback può essere eseguito contemporaneamente su due thread del pool di thread se l'intervallo timer è inferiore al tempo necessario per eseguire il callback oppure se tutti i thread del pool di thread sono in uso e il callback viene accodato più volte.

Nota

System.Threading.Timer è un timer semplice e leggero che usa metodi di callback e viene gestito dai thread del pool di thread. Non è consigliabile usare con Windows Form, perché i relativi callback non si verificano nel thread dell'interfaccia utente. System.Windows.Forms.Timer è una scelta migliore per l'uso con Windows Form. Per la funzionalità timer basata su server, è possibile prendere in considerazione l'uso di System.Timers.Timer, che genera eventi e include funzionalità aggiuntive.

Costruttori

Timer(TimerCallback)

Inizializza una nuova istanza della classe Timer con un periodo infinito e un tempo di scadenza infinito, utilizzando l'oggetto Timer appena creato come oggetto di stato.

Timer(TimerCallback, Object, Int32, Int32)

Inizializza una nuova istanza della classe Timer utilizzando un intero con segno a 32 bit per specificare l'intervallo di tempo.

Timer(TimerCallback, Object, Int64, Int64)

Inizializza una nuova istanza della classe Timer utilizzando interi con segno a 64 bit per misurare gli intervalli di tempo.

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

Inizializza una nuova istanza della classe Timer utilizzando TimeSpan valori per misurare gli intervalli di tempo.

Timer(TimerCallback, Object, UInt32, UInt32)

Inizializza una nuova istanza della classe Timer utilizzando interi senza segno a 32 bit per misurare gli intervalli di tempo.

Proprietà

ActiveCount

Ottiene il numero di timer attualmente attivi. Un timer attivo viene registrato per il tick in un determinato momento in futuro e non è ancora stato annullato.

Metodi

Change(Int32, Int32)

Modifica l'ora di inizio e l'intervallo tra le chiamate al metodo per un timer, usando interi con segno a 32 bit per misurare gli intervalli di tempo.

Change(Int64, Int64)

Modifica l'ora di inizio e l'intervallo tra le chiamate al metodo per un timer, usando interi con segno a 64 bit per misurare gli intervalli di tempo.

Change(TimeSpan, TimeSpan)

Modifica l'ora di inizio e l'intervallo tra le chiamate al metodo per un timer, utilizzando TimeSpan valori per misurare gli intervalli di tempo.

Change(UInt32, UInt32)

Modifica l'ora di inizio e l'intervallo tra le chiamate al metodo per un timer, usando interi senza segno a 32 bit per misurare gli intervalli di tempo.

CreateObjRef(Type)

Crea un oggetto che contiene tutte le informazioni pertinenti necessarie per generare un proxy utilizzato per comunicare con un oggetto remoto.

(Ereditato da MarshalByRefObject)
Dispose()

Rilascia tutte le risorse usate dall'istanza corrente di Timer.

Dispose(WaitHandle)

Rilascia tutte le risorse usate dall'istanza corrente di Timer e segnala quando il timer è stato eliminato.

DisposeAsync()

Rilascia tutte le risorse usate dall'istanza corrente di Timer.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Finalize()

Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperata da Garbage Collection.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Recupera l'oggetto servizio di durata corrente che controlla i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleti.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia superficiale dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Metodi di estensione

ConfigureAwait(IAsyncDisposable, Boolean)

Configura il modo in cui verranno eseguite le attese nelle attività restituite da un oggetto eliminabile asincrono.

Si applica a

Thread safety

Questo tipo è thread-safe.

Vedi anche