Timer.Enabled Timer.Enabled Timer.Enabled Timer.Enabled Property

Definição

Obtém ou define um valor que indica se o Timer deve acionar o evento Elapsed.Gets or sets a value indicating whether the Timer should raise the Elapsed event.

public:
 property bool Enabled { bool get(); void set(bool value); };
[System.Timers.TimersDescription("Indicates whether the timer is enabled to fire events at a defined interval.")]
[System.Timers.TimersDescription("TimerEnabled")]
public bool Enabled { get; set; }
member this.Enabled : bool with get, set
Public Property Enabled As Boolean

Valor da propriedade

true caso o Timer deva acionar o evento Elapsed; caso contrário, false.true if the Timer should raise the Elapsed event; otherwise, false. O padrão é false.The default is false.

Exceções

Essa propriedade não pode ser definida porque o temporizador foi descartado.This property cannot be set because the timer has been disposed.

A propriedade Interval foi definida como um valor maior que MaxValue antes de o temporizador ser habilitado.The Interval property was set to a value greater than MaxValue before the timer was enabled.

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

Definindo Enabled à true é o mesmo que chamar Start, enquanto a configuração Enabled para false é o mesmo que chamar Stop.Setting Enabled to true is the same as calling Start, while setting Enabled to false is the same as calling Stop.

Observação

O sinal para gerar a Elapsed eventos sempre foi enfileirado para execução em um ThreadPool thread.The signal to raise the Elapsed event is always queued for execution on a ThreadPool thread. Isso pode resultar no Elapsed evento sendo gerado após o Enabled estiver definida como false.This might result in the Elapsed event being raised after the Enabled property is set to false. O exemplo de código para o Stop método mostra uma maneira de contornar essa condição de corrida.The code example for the Stop method shows one way to work around this race condition.

Se Enabled é definido como true e AutoReset é definido como false, o Timer aciona o Elapsed eventos somente uma vez, na primeira vez que o intervalo tenha decorrido.If Enabled is set to true and AutoReset is set to false, the Timer raises the Elapsed event only once, the first time the interval elapses.

Se o intervalo é definido após o Timer tiver iniciado, a contagem é redefinida.If the 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 as Enabled propriedade para true, a contagem começa no momento Enabled está definido.For example, if you set the interval to 5 seconds and then set the Enabled property 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.

Observação

Alguns designers visuais, como aqueles no Microsoft Visual Studio, defina as Enabled propriedade para true ao inserir um novo Timer.Some visual designers, such as those in Microsoft Visual Studio, set the Enabled property to true when inserting a new Timer.

Aplica-se a

Veja também