Timer Classe

Definizione

Fornisce un meccanismo per eseguire un metodo su un thread del pool di thread a intervalli specificati. La 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 che include un StatusCheckerCheckStatus metodo la cui firma è uguale al TimerCallback delegato. L'argomento stateCheckStatus del metodo è un AutoResetEvent oggetto utilizzato per sincronizzare il thread dell'applicazione e il thread del pool di thread che esegue il delegato di callback. La StatusChecker classe include anche due variabili di stato:

invokeCount Indica il numero di volte in cui è stato richiamato il metodo di callback.

maxCount Determina il numero massimo di volte in cui deve essere richiamato il metodo di callback.

Il thread dell'applicazione crea il timer, che attende un secondo e quindi esegue il CheckStatus metodo di callback ogni 250 millisecondi. Il thread dell'applicazione blocca quindi finché l'oggetto AutoResetEvent non viene segnalato. Quando il metodo callback viene eseguito maxCount in tempo, chiama il AutoResetEvent.SetCheckStatus metodo per impostare lo stato dell'oggetto AutoResetEvent su segnalato. La prima volta che si verifica questo problema, il thread dell'applicazione chiama il metodo in modo che il Change(Int32, Int32) metodo di callback venga eseguito ogni metà del secondo. Blocca ancora una volta finché l'oggetto AutoResetEvent non viene segnalato. In questo caso, il timer viene distrutto chiamando il Dispose relativo metodo 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 TimerCallback delegato per specificare il metodo da Timer eseguire. La firma del TimerCallback delegato è:

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 nel thread che ha creato il timer; viene eseguito su un ThreadPool thread fornito dal sistema.

Suggerimento

.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 servizio in un ambiente multithreading; non ha interfaccia utente e non è visibile in fase di esecuzione.
  • System.Threading.Timer, che esegue un singolo metodo di callback in 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, questa System.Timers.Timer classe è destinata all'uso come componente basato su server o servizio in un ambiente multithreaded. Non ha interfaccia utente e non è visibile in fase di esecuzione.
  • System.Windows.Forms.Timer, un componente Windows Forms 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 Dispatcher coda. Questo timer viene elaborato con una priorità specificata a un intervallo di tempo specificato.

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

Nota

Purché si usi un Timeroggetto , è necessario mantenere un riferimento a esso. Come per qualsiasi oggetto gestito, un Timer oggetto è soggetto a Garbage Collection quando non sono presenti riferimenti. Il fatto che un oggetto Timer è ancora attivo non impedisce che venga raccolto.

Nota

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

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

Il metodo di callback eseguito dal timer deve essere reentrant, perché viene chiamato nei ThreadPool thread. Il callback può essere eseguito simultaneamente in due thread del pool di thread se l'intervallo timer è minore del tempo necessario per eseguire il callback o 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 i metodi di callback e viene servito dai thread del pool di thread. Non è consigliabile usare con Windows Forms, perché i callback non si verificano nel thread dell'interfaccia utente. System.Windows.Forms.Timerè una scelta migliore per l'uso con Windows Forms. Per le funzionalità timer basate sul server, è possibile usare System.Timers.Timer, che genera eventi e include funzionalità aggiuntive.

Costruttori

Timer(TimerCallback)

Inizializza una nuova istanza della classe Timer con un periodo e un' ora di esecuzione infiniti, utilizzando l'oggetto Timer appena creato come oggetto di stato.

Timer(TimerCallback, Object, Int32, Int32)

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

Timer(TimerCallback, Object, Int64, Int64)

Consente l'inizializzazione di una nuova istanza della classe Timer utilizzando integer con segno a 64 bit per misurare gli intervalli di tempo.

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

Consente l'inizializzazione di una nuova istanza della classe Timer utilizzando i valori TimeSpan per misurare gli intervalli di tempo.

Timer(TimerCallback, Object, UInt32, UInt32)

Consente l'inizializzazione di una nuova istanza della classe Timer utilizzando integer senza segno a 32 bit per misurare gli intervalli di tempo.

Proprietà

ActiveCount

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

Metodi

Change(Int32, Int32)

Modifica l'ora di inizio e l'intervallo tra le chiamate dei metodi di 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 dei metodi di un timer, usando interi con segno a 64 bit per misurare gli intervalli di tempo.

Change(TimeSpan, TimeSpan)

Consente di modificare il tempo di attesa e gli intervalli tra i richiami di un timer utilizzando i valori di TimeSpan per misurare gli intervalli di tempo.

Change(UInt32, UInt32)

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

CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
Dispose()

Consente di rilasciare tutte le risorse utilizzate dall'istanza corrente di Timer.

Dispose(WaitHandle)

Consente di rilasciare tutte le risorse utilizzate dall'istanza corrente di Timer segnalando l'ora dell'eliminazione del timer.

DisposeAsync()

Consente di rilasciare tutte le risorse utilizzate 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 effettuare un tentativo di liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperato da Garbage Collection.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleti.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene l'oggetto 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 dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti 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)

Consente di configurare la modalità di esecuzione delle espressioni await per le attività restituite da un elemento disposable asincrono.

Si applica a

Thread safety

Questo tipo è thread-safe.

Vedi anche