Leer en inglés

Compartir a través de


TimerCallback Delegado

Definición

Representa el método que controla las llamadas de un Timer.

C#
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void TimerCallback(object state);
C#
public delegate void TimerCallback(object? state);
C#
public delegate void TimerCallback(object state);

Parámetros

state
Object

Objeto que contiene información específica de la aplicación relativa al método invocado por este delegado, o null.

Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear el delegado usado con la Timer clase .

C#
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.

Comentarios

Use un TimerCallback delegado para especificar el método al que llama un Timer. Este método no se ejecuta en el subproceso que creó el temporizador; se ejecuta en un subproceso de grupo de subprocesos independiente proporcionado por el sistema. El TimerCallback delegado invoca el método una vez después de que transcurre la hora de inicio y continúa invocándolo una vez por intervalo de temporizador hasta que se llame al Dispose método o hasta que se llame al Timer.Change método con el valor Infiniteinterval .

Nota

Las devoluciones de llamada pueden producirse después de llamar a la sobrecarga del Dispose() método, ya que el temporizador pone en cola devoluciones de llamada para su ejecución por subprocesos del grupo de subprocesos. Puede usar la sobrecarga del Dispose(WaitHandle) método para esperar hasta que se hayan completado todas las devoluciones de llamada.

El delegado del temporizador se especifica cuando se construye el temporizador y no se puede cambiar. La hora de inicio de se Timer pasa en el dueTime parámetro de los Timer constructores y el período se pasa en el period parámetro . Para ver un ejemplo que muestra cómo crear y usar un TimerCallback delegado, vea System.Threading.Timer.

Métodos de extensión

GetMethodInfo(Delegate)

Obtiene un objeto que representa el método representado por el delegado especificado.

Se aplica a

Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Consulte también