Timer.Elapsed Timer.Elapsed Timer.Elapsed Timer.Elapsed Event

Definição

Ocorre quando o intervalo termina.Occurs when the interval elapses.

public:
 event System::Timers::ElapsedEventHandler ^ Elapsed;
[System.Timers.TimersDescription("Occurs when the Interval has elapsed.")]
[System.Timers.TimersDescription("TimerIntervalElapsed")]
public event System.Timers.ElapsedEventHandler Elapsed;
member this.Elapsed : System.Timers.ElapsedEventHandler 
Public Custom Event Elapsed As ElapsedEventHandler 
Atributos

Exemplos

O exemplo a seguir instancia um Timer objeto que dispara seu Timer.Elapsed evento a cada dois segundos (2000 milissegundos), configura um manipulador de eventos para o evento e inicia o temporizador.The following example instantiates a Timer object that fires its Timer.Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. O manipulador de eventos exibe o valor da ElapsedEventArgs.SignalTime Propriedade cada vez que é gerado.The event handler displays the value of the ElapsedEventArgs.SignalTime property each time it is raised.

using namespace System;
using namespace System::Timers;

public ref class Example
{
private:
    static System::Timers::Timer^ aTimer;

public:
    static void Demo()
    {
        // Create a timer and set a two second interval.
        aTimer = gcnew System::Timers::Timer();
        aTimer->Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler(Example::OnTimedEvent);

        // Have the timer fire repeated events (true is the default)
        aTimer->AutoReset = true;

        // Start the timer
        aTimer->Enabled = true;

        Console::WriteLine("Press the Enter key to exit the program at any time... ");
        Console::ReadLine();
    }

private:
    static void OnTimedEvent(Object^ source, System::Timers::ElapsedEventArgs^ e)
    {
        Console::WriteLine("The Elapsed event was raised at {0}", e->SignalTime);
    }
};

int main()
{
    Example::Demo();
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM 

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM 
Imports System.Timers

Public Module Example
    Private aTimer As Timer

    Public Sub Main()
        ' Create a timer and set a two second interval.
        aTimer = New System.Timers.Timer()
        aTimer.Interval = 2000

        ' Hook up the Elapsed event for the timer.  
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

        ' Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = True

        ' Start the timer
        aTimer.Enabled = True

        Console.WriteLine("Press the Enter key to exit the program at any time... ")
        Console.ReadLine()
    End Sub

    Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub
End Module
' The example displays output like the following: 
'       Press the Enter key to exit the program at any time... 
'       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:06 PM 

Comentários

O Elapsed evento será gerado se a Enabled propriedade for true e o intervalo de tempo Interval (em milissegundos) definido pela propriedade estiver decorrido.The Elapsed event is raised if the Enabled property is true and the time interval (in milliseconds) defined by the Interval property elapses. Se a AutoReset propriedade for true, o evento será gerado repetidamente em Interval um intervalo definido pela propriedade; caso contrário, o evento será gerado apenas uma vez, na primeira vez Interval que o valor decorrerá.If the AutoReset property is true, the event is raised repeatedly at an interval defined by the Interval property; otherwise, the event is raised only once, the first time the Interval value elapses.

Se Interval for definido após o Timer iniciado, a contagem será redefinida.If Interval is set after the Timer has started, the count is reset. Por exemplo, se você definir o intervalo como 5 segundos e, em Enabled seguida true, definido como, a contagem começará no momento Enabled em que for definida.For example, if you set the interval to 5 seconds and then set Enabled to true, the count starts at the time Enabled is set. Se você redefinir o intervalo para 10 segundos quando a contagem for de 3 segundos Elapsed , o evento será gerado pela primeira vez em 13 Enabled segundos após ser truedefinido como.If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.

Se a SynchronizingObject propriedade for null, o Elapsed evento será gerado em um ThreadPool thread.If the SynchronizingObject property is null,the Elapsed event is raised on a ThreadPool thread. Se o processamento do Elapsed evento durar mais que Interval, o evento poderá ser gerado novamente em outro ThreadPool thread.If the processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Nessa situação, o manipulador de eventos deve ser reentrante.In this situation, the event handler should be reentrant.

Observação

O método de manipulação de eventos pode ser executado em um thread ao mesmo tempo em que outro thread Stop chama o método ou Enabled define a falsePropriedade como.The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false. Isso pode fazer com que Elapsed o evento seja gerado depois que o temporizador for interrompido.This might result in the Elapsed event being raised after the timer is stopped. O código de exemplo para Stop o método mostra uma maneira de evitar essa condição de corrida.The example code for the Stop method shows one way to avoid this race condition.

Mesmo se SynchronizingObject não nullfor, Elapsed os eventos poderão ocorrer depois Dispose que Stop o método ou tiver sido chamado ou Enabled depois que a propriedade tiver falsesido definida como, porque o sinal para gerar o Elapsed o evento é sempre enfileirado para execução em um thread do pool de threads.Even if SynchronizingObject is not null, Elapsed events can occur after the Dispose or Stop method has been called or after the Enabled property has been set to false, because the signal to raise the Elapsed event is always queued for execution on a thread pool thread. Uma maneira de resolver essa condição de corrida é definir um sinalizador que informa ao manipulador de eventos para Elapsed que o evento ignore os eventos subsequentes.One way to resolve this race condition is to set a flag that tells the event handler for the Elapsed event to ignore subsequent events.

O Timer componente captura e suprime todas as exceções geradas pelos manipuladores de eventos Elapsed para o evento.The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. Esse comportamento está sujeito a alterações em versões futuras do .NET Framework.This behavior is subject to change in future releases of the .NET Framework.

Aplica-se a

Veja também