Timer Constructores

Definición

Inicializa una nueva instancia de la clase Timer.

Sobrecargas

Timer(TimerCallback)

Inicializa una nueva instancia de la clase Timer con un período y un tiempo límite infinitos, utilizando el objeto Timer recién creado como objeto de estado.

Timer(TimerCallback, Object, Int32, Int32)

Inicializa una nueva instancia de la clase Timer utilizando un entero de 32 bits con signo para medir los intervalos de tiempo.

Timer(TimerCallback, Object, Int64, Int64)

Inicializa una nueva instancia de la clase Timer utilizando un entero de 64 bits con signo para medir los intervalos de tiempo.

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

Inicializa una nueva instancia de la clase Timer, utilizando valores de TimeSpan para medir los intervalos de tiempo.

Timer(TimerCallback, Object, UInt32, UInt32)

Inicializa una nueva instancia de la clase Timer utilizando un entero de 32 bits sin signo para medir los intervalos de tiempo.

Timer(TimerCallback)

Inicializa una nueva instancia de la clase Timer con un período y un tiempo límite infinitos, utilizando el objeto Timer recién creado como objeto de estado.

public:
 Timer(System::Threading::TimerCallback ^ callback);
public Timer (System.Threading.TimerCallback callback);
new System.Threading.Timer : System.Threading.TimerCallback -> System.Threading.Timer
Public Sub New (callback As TimerCallback)

Parámetros

callback
TimerCallback

Delegado de TimerCallback que representa un método que se debe ejecutar.

Ejemplos

En el ejemplo de código siguiente se crea un nuevo temporizador, utilizando el propio temporizador como objeto de estado. El Change método se usa para iniciar el temporizador. Cuando se produce la devolución de llamada del temporizador, el objeto de estado se usa para desactivar el temporizador.

using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create an instance of the Example class, and start two
        // timers.
        Example ex = new Example();
        ex.StartTimer(2000);
        ex.StartTimer(1000);

        Console.WriteLine("Press Enter to end the program.");
        Console.ReadLine();
    }

    public void StartTimer(int dueTime)
    {
        Timer t = new Timer(new TimerCallback(TimerProc));
        t.Change(dueTime, 0);
    }

    private void TimerProc(object state)
    {
        // The state object is the Timer object.
        Timer t = (Timer) state;
        t.Dispose();
        Console.WriteLine("The timer callback executes.");
    }
}
Imports System.Threading

Public Class Example
    Public Shared Sub Main()
        ' Create an instance of the Example class, and start two
        ' timers.
        Dim ex As New Example()
        ex.StartTimer(2000)
        ex.StartTimer(1000)

        Console.WriteLine("Press Enter to end the program.")
        Console.ReadLine()
    End Sub

    Public Sub StartTimer(ByVal dueTime As Integer)
        Dim t As New Timer(AddressOf TimerProc)
        t.Change(dueTime, 0)
    End Sub

    Private Sub TimerProc(ByVal state As Object)
        ' The state object is the Timer object.
        Dim t As Timer = CType(state, Timer)
        t.Dispose()
        Console.WriteLine("The timer callback executes.")
    End Sub
End Class

Comentarios

Llame a este constructor cuando desee usar el Timer propio objeto como objeto de estado. Después de crear el temporizador, use el Change método para establecer el intervalo y el tiempo de vencimiento.

Este constructor especifica un tiempo de vencimiento infinito antes de la primera devolución de llamada y un intervalo infinito entre devoluciones de llamada, con el fin de evitar que la primera devolución de llamada se produzca antes de que el Timer objeto se asigne al objeto de estado.

El método especificado para callback debe ser reentrant, porque se llama a en ThreadPool subprocesos. El método se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar el método, o si todos los subprocesos del grupo de subprocesos están en uso y el método se pone en cola varias veces.

Se aplica a

Timer(TimerCallback, Object, Int32, Int32)

Inicializa una nueva instancia de la clase Timer utilizando un entero de 32 bits con signo para medir los intervalos de tiempo.

public:
 Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, int dueTime, int period);
public Timer (System.Threading.TimerCallback callback, object state, int dueTime, int period);
public Timer (System.Threading.TimerCallback callback, object? state, int dueTime, int period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * int * int -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As Integer, period As Integer)

Parámetros

callback
TimerCallback

Delegado de TimerCallback que representa un método que se debe ejecutar.

state
Object

Objeto que contiene información que debe utilizar el método de devolución de llamada, o null.

dueTime
Int32

Período de tiempo de retraso, en milisegundos, antes de que se invoque a callback. Especifique Infinite para evitar que se inicie el temporizador. Especifique cero (0) para iniciar inmediatamente el temporizador.

period
Int32

Intervalo de tiempo, en milisegundos, entre las distintas invocaciones de callback. Especifique Infinite para deshabilitar la señalización periódica.

Excepciones

El parámetro dueTime o period es negativo y no es igual a Infinite.

El parámetro callback es null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear un TimerCallback delegado e inicializar una nueva instancia de la Timer clase .

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.

Comentarios

El delegado especificado por el callback parámetro se invoca una vez transcurrido dueTime y, a continuación, cada vez que transcurre el period intervalo de tiempo.

Si dueTime es cero (0), callback se invoca inmediatamente. Si dueTime es Timeout.Infinite, callback no se invoca; el temporizador está deshabilitado, pero se puede volver a habilitar llamando al Change método .

Dado que la Timer clase tiene la misma resolución que el reloj del sistema, que es aproximadamente de 15 milisegundos en los sistemas Windows 7 y Windows 8, el callback delegado se ejecuta a intervalos definidos por la resolución del reloj del sistema si period es menor que la resolución del reloj del sistema. Si period es cero (0) o Timeout.Infinite y dueTime no Timeout.Infinitees , callback se invoca una vez; el comportamiento periódico del temporizador está deshabilitado, pero se puede volver a habilitar mediante el Change método .

Nota:

El reloj del sistema que se usa es el mismo reloj utilizado por GetTickCount, que no se ve afectado por los cambios realizados con timeBeginPeriod y timeEndPeriod.

El método especificado para callback debe ser reentrant, porque se llama a en ThreadPool subprocesos. El método se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar el método, o si todos los subprocesos del grupo de subprocesos están en uso y el método se pone en cola varias veces.

Consulte también

Se aplica a

Timer(TimerCallback, Object, Int64, Int64)

Inicializa una nueva instancia de la clase Timer utilizando un entero de 64 bits con signo para medir los intervalos de tiempo.

public:
 Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, long dueTime, long period);
public Timer (System.Threading.TimerCallback callback, object? state, long dueTime, long period);
public Timer (System.Threading.TimerCallback callback, object state, long dueTime, long period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * int64 * int64 -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As Long, period As Long)

Parámetros

callback
TimerCallback

Delegado de TimerCallback que representa un método que se debe ejecutar.

state
Object

Objeto que contiene información que debe utilizar el método de devolución de llamada, o null.

dueTime
Int64

Período de tiempo de retraso, en milisegundos, antes de que se invoque a callback. Especifique Infinite para evitar que se inicie el temporizador. Especifique cero (0) para iniciar inmediatamente el temporizador.

period
Int64

Intervalo de tiempo, en milisegundos, entre las distintas invocaciones de callback. Especifique Infinite para deshabilitar la señalización periódica.

Excepciones

El parámetro dueTime o period es negativo y no es igual a Infinite.

El parámetro dueTime o period es mayor que 4294967294.

Comentarios

El delegado especificado por el callback parámetro se invoca una vez transcurrido dueTime y, a continuación, cada vez que transcurre el period intervalo de tiempo.

Si dueTime es cero (0), callback se invoca inmediatamente. Si dueTime es Timeout.Infinite, callback no se invoca; el temporizador está deshabilitado, pero se puede volver a habilitar llamando al Change método .

Dado que la Timer clase tiene la misma resolución que el reloj del sistema, que es aproximadamente de 15 milisegundos en los sistemas Windows 7 y Windows 8, el callback delegado se ejecuta a intervalos definidos por la resolución del reloj del sistema si period es menor que la resolución del reloj del sistema. Si period es cero (0) o Timeout.Infinite y dueTime no Timeout.Infinitees , callback se invoca una vez; el comportamiento periódico del temporizador está deshabilitado, pero se puede volver a habilitar mediante el Change método .

Nota:

El reloj del sistema que se usa es el mismo reloj utilizado por GetTickCount, que no se ve afectado por los cambios realizados con timeBeginPeriod y timeEndPeriod.

El método especificado para callback debe ser reentrant, porque se llama a en ThreadPool subprocesos. El método se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar el método, o si todos los subprocesos del grupo de subprocesos están en uso y el método se pone en cola varias veces.

Consulte también

Se aplica a

Timer(TimerCallback, Object, TimeSpan, TimeSpan)

Inicializa una nueva instancia de la clase Timer, utilizando valores de TimeSpan para medir los intervalos de tiempo.

public:
 Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, TimeSpan dueTime, TimeSpan period);
public Timer (System.Threading.TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);
public Timer (System.Threading.TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * TimeSpan * TimeSpan -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As TimeSpan, period As TimeSpan)

Parámetros

callback
TimerCallback

Delegado que representa un método que se va a ejecutar.

state
Object

Objeto que contiene información que debe utilizar el método de devolución de llamada, o null.

dueTime
TimeSpan

Período de tiempo de retraso antes de que se invoque a callback. Especifique InfiniteTimeSpan para evitar que se inicie el temporizador. Especifique Zero para iniciar inmediatamente el temporizador.

period
TimeSpan

Intervalo de tiempo entre las distintas invocaciones de callback. Especifique InfiniteTimeSpan para deshabilitar la señalización periódica.

Excepciones

El número de milisegundos en el valor de dueTime o period es negativo y no es igual a Infinite, o es mayor que Int32.MaxValue.

El parámetro callback es null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear un TimerCallback delegado e inicializar una nueva instancia de la Timer clase .

using namespace System;
using namespace System::Threading;
ref class StatusChecker
{
private:
   int invokeCount;
   int 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} Checking status {1,2}.", DateTime::Now.ToString(  "h:mm:ss.fff" ), (++invokeCount).ToString() );
      if ( invokeCount == maxCount )
      {
         
         // Reset the counter and signal main.
         invokeCount = 0;
         autoEvent->Set();
      }
   }

};

int main()
{
   AutoResetEvent^ autoEvent = gcnew AutoResetEvent( false );
   StatusChecker^ statusChecker = gcnew StatusChecker( 10 );
   
   // Create the delegate that invokes methods for the timer.
   TimerCallback^ timerDelegate = gcnew TimerCallback( statusChecker, &StatusChecker::CheckStatus );
   TimeSpan delayTime = TimeSpan(0,0,1);
   TimeSpan intervalTime = TimeSpan(0,0,0,0,250);
   
   // Create a timer that signals the delegate to invoke CheckStatus 
   // after one second, and every 1/4 second thereafter.
   Console::WriteLine( "{0} Creating timer.\n", DateTime::Now.ToString(  "h:mm:ss.fff" ) );
   Timer^ stateTimer = gcnew Timer( timerDelegate,autoEvent,delayTime,intervalTime );
   
   // When autoEvent signals, change the period to every 1/2 second.
   autoEvent->WaitOne( 5000, false );
   stateTimer->Change( TimeSpan(0), intervalTime + intervalTime );
   Console::WriteLine( "\nChanging period.\n" );
   
   // When autoEvent signals the second time, dispose of the timer.
   autoEvent->WaitOne( 5000, false );
   stateTimer->~Timer();
   Console::WriteLine( "\nDestroying timer." );
}
using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        TimeSpan delayTime = new TimeSpan(0, 0, 1);
        TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = new Timer(
            timerDelegate, autoEvent, delayTime, intervalTime);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(new TimeSpan(0), 
            intervalTime + intervalTime);
        Console.WriteLine("\nChanging period.\n");

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

class StatusChecker
{
    int invokeCount, 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 Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}
Imports System.Threading

Public Class TimerExample

    <MTAThread> _
    Shared Sub Main()
    
        Dim autoEvent As New AutoResetEvent(False)
        Dim statusChecker As New StatusChecker(10)

        ' Create the delegate that invokes methods for the timer.
        Dim timerDelegate As TimerCallback = _
            AddressOf statusChecker.CheckStatus

        Dim delayTime As New TimeSpan(0, 0, 1)
        Dim intervalTime As New TimeSpan(0, 0, 0, 0, 250)

        ' Create a timer that signals the delegate to invoke 
        ' CheckStatus after one second, and every 1/4 second 
        ' thereafter.
        Console.WriteLine("{0} Creating timer." & vbCrLf, _
            DateTime.Now.ToString("h:mm:ss.fff"))
        Dim stateTimer As Timer = New Timer( _
            timerDelegate, autoEvent, delayTime, intervalTime)

        ' When autoEvent signals, change the period to every 
        ' 1/2 second.
        autoEvent.WaitOne(5000, False)
        stateTimer.Change( _
            new TimeSpan(0), intervalTime.Add(intervalTime))
        Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)

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

Public Class StatusChecker

    Dim invokeCount, maxCount As Integer 

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

    ' This method is called by the timer delegate.
    Sub CheckStatus(stateInfo As Object)
        Dim autoEvent As AutoResetEvent = _
            DirectCast(stateInfo, AutoResetEvent)
        invokeCount += 1
        Console.WriteLine("{0} Checking status {1,2}.", _
            DateTime.Now.ToString("h:mm:ss.fff"), _
            invokeCount.ToString())

        If invokeCount = maxCount Then
        
            ' Reset the counter and signal to stop the timer.
            invokeCount  = 0
            autoEvent.Set()
        End If
    End Sub

End Class

Comentarios

El delegado especificado por el callback parámetro se invoca una vez transcurrido dueTime y, a continuación, cada vez que transcurre el period intervalo de tiempo.

Si dueTime es cero (0), callback se invoca inmediatamente. Si dueTime es negativo uno (-1) milisegundos, no se invoca; callback el temporizador está deshabilitado, pero se puede volver a habilitar llamando al Change método .

Dado que la Timer clase tiene la misma resolución que el reloj del sistema, que es aproximadamente de 15 milisegundos en los sistemas Windows 7 y Windows 8, el callback delegado se ejecuta a intervalos definidos por la resolución del reloj del sistema si period es menor que la resolución del reloj del sistema. Si period es cero (0) o negativo uno (-1) milisegundos y dueTime es positivo, callback se invoca una vez; el comportamiento periódico del temporizador está deshabilitado, pero se puede volver a habilitar mediante el Change método .

Nota:

El reloj del sistema que se usa es el mismo reloj utilizado por GetTickCount, que no se ve afectado por los cambios realizados con timeBeginPeriod y timeEndPeriod.

El método especificado para callback debe ser reentrant, porque se llama a en ThreadPool subprocesos. El método se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar el método, o si todos los subprocesos del grupo de subprocesos están en uso y el método se pone en cola varias veces.

Consulte también

Se aplica a

Timer(TimerCallback, Object, UInt32, UInt32)

Importante

Esta API no es conforme a CLS.

Inicializa una nueva instancia de la clase Timer utilizando un entero de 32 bits sin signo para medir los intervalos de tiempo.

public:
 Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, System::UInt32 dueTime, System::UInt32 period);
[System.CLSCompliant(false)]
public Timer (System.Threading.TimerCallback callback, object? state, uint dueTime, uint period);
[System.CLSCompliant(false)]
public Timer (System.Threading.TimerCallback callback, object state, uint dueTime, uint period);
[<System.CLSCompliant(false)>]
new System.Threading.Timer : System.Threading.TimerCallback * obj * uint32 * uint32 -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As UInteger, period As UInteger)

Parámetros

callback
TimerCallback

Delegado que representa un método que se va a ejecutar.

state
Object

Objeto que contiene información que debe utilizar el método de devolución de llamada, o null.

dueTime
UInt32

Período de tiempo de retraso, en milisegundos, antes de que se invoque a callback. Especifique Infinite para evitar que se inicie el temporizador. Especifique cero (0) para iniciar inmediatamente el temporizador.

period
UInt32

Intervalo de tiempo, en milisegundos, entre las distintas invocaciones de callback. Especifique Infinite para deshabilitar la señalización periódica.

Atributos

Excepciones

El parámetro dueTime o period es negativo y no es igual a Infinite.

El parámetro callback es null.

Comentarios

El delegado especificado por el callback parámetro se invoca una vez transcurrido dueTime y, a continuación, cada vez que transcurre el period intervalo de tiempo.

Si dueTime es cero (0), callback se invoca inmediatamente. Si dueTime es Timeout.Infinite, callback no se invoca; el temporizador está deshabilitado, pero se puede volver a habilitar llamando al Change método .

Dado que la Timer clase tiene la misma resolución que el reloj del sistema, que es aproximadamente de 15 milisegundos en los sistemas Windows 7 y Windows 8, el callback delegado se ejecuta a intervalos definidos por la resolución del reloj del sistema si period es menor que la resolución del reloj del sistema. Si period es cero (0) o Timeout.Infinite y dueTime no Timeout.Infinitees , callback se invoca una vez; el comportamiento periódico del temporizador está deshabilitado, pero se puede volver a habilitar mediante el Change método .

Nota

El reloj del sistema que se usa es el mismo reloj utilizado por GetTickCount, que no se ve afectado por los cambios realizados con timeBeginPeriod y timeEndPeriod.

El método especificado para callback debe ser reentrant, ya que se llama a en ThreadPool subprocesos. El método se puede ejecutar simultáneamente en dos subprocesos del grupo de subprocesos si el intervalo del temporizador es menor que el tiempo necesario para ejecutar el método, o si todos los subprocesos del grupo de subprocesos están en uso y el método se pone en cola varias veces.

Consulte también

Se aplica a