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 aciona seu Timer.Elapsed eventos 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 ele é acionado.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á acionado se o Enabled é de propriedade true e o intervalo de tempo (em milissegundos) definido pelo Interval ter decorrido de propriedade.The Elapsed event is raised if the Enabled property is true and the time interval (in milliseconds) defined by the Interval property elapses. Se o AutoReset é de propriedade true, o evento é acionado repetidamente em um intervalo definido pela Interval propriedade; caso contrário, o evento é gerado apenas uma vez, na primeira vez o Interval valor tiver decorrido.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 é definido após o Timer tiver iniciado, a contagem é redefinida.If Interval is set after the Timer has started, the count is reset. Por exemplo, se você definir o intervalo de 5 segundos e, em seguida, defina Enabled à true, a contagem começa no momento Enabled está definido.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 de 10 segundos quando a contagem for 3 segundos, o Elapsed é gerado pela primeira vez e 13 segundos após Enabled foi definida como true.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 o SynchronizingObject é de propriedade null, o Elapsed evento é gerado em um ThreadPool thread.If the SynchronizingObject property is null,the Elapsed event is raised on a ThreadPool thread. Se o processamento das Elapsed evento dura mais de Interval, o evento pode 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 que outro thread chama o Stop método ou define o Enabled propriedade para false.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 resultar no Elapsed evento sendo gerado depois que o temporizador será interrompido.This might result in the Elapsed event being raised after the timer is stopped. O exemplo de código para o Stop 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 é null, Elapsed eventos podem ocorrer após a Dispose ou Stop método foi chamado ou depois o Enabled propriedade foi definida como false, pois o sinal para gerar o Elapsed eventos sempre foi enfileirado para execução em um 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 o Elapsed evento ignorar 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 de captura e suprime todas as exceções lançadas por manipuladores de eventos para o Elapsed eventos.The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. Esse comportamento está sujeita 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