Timer.Enabled Свойство

Определение

Возвращает или задает значение, определяющее, должен ли объект Timer вызывать событие 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); };
public bool Enabled { get; set; }
[System.Timers.TimersDescription("TimerEnabled")]
public bool Enabled { get; set; }
[System.Timers.TimersDescription("Indicates whether the timer is enabled to fire events at a defined interval.")]
public bool Enabled { get; set; }
member this.Enabled : bool with get, set
[<System.Timers.TimersDescription("TimerEnabled")>]
member this.Enabled : bool with get, set
[<System.Timers.TimersDescription("Indicates whether the timer is enabled to fire events at a defined interval.")>]
member this.Enabled : bool with get, set
Public Property Enabled As Boolean

Значение свойства

Boolean

Значение true, если объект Timer должен вызывать событие Elapsed; в противном случае — false.true if the Timer should raise the Elapsed event; otherwise, false. Значение по умолчанию — false.The default is false.

Атрибуты

Исключения

Данное свойство задать нельзя, так как таймер удален.This property cannot be set because the timer has been disposed.

Перед включением таймера свойству Interval задано значение больше MaxValue.The Interval property was set to a value greater than MaxValue before the timer was enabled.

Примеры

В следующем примере создается экземпляр Timer объекта, который запускает Timer.Elapsed событие каждые две секунды (2000 миллисекунд), настраивает обработчик событий для события и запускает таймер.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. Обработчик событий отображает значение ElapsedEventArgs.SignalTime свойства при каждом его возникновении.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 

Комментарии

Параметр Enabled true имеет то же значение, что и вызов Start , тогда как параметр Enabled false равен вызову Stop .Setting Enabled to true is the same as calling Start, while setting Enabled to false is the same as calling Stop.

Примечание

Сигнал для вызова Elapsed события всегда находится в очереди на выполнение в ThreadPool потоке.The signal to raise the Elapsed event is always queued for execution on a ThreadPool thread. Это может привести к Elapsed возникновению события после того, как Enabled свойство имеет значение false .This might result in the Elapsed event being raised after the Enabled property is set to false. В примере кода для Stop метода показан один из способов обхода этого состояния гонки.The code example for the Stop method shows one way to work around this race condition.

Если параметр Enabled имеет значение true и AutoReset имеет значение false , то Timer событие вызывается Elapsed только один раз, когда истечет интервал времени.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.

Если интервал установлен после Timer начала, счетчик сбрасывается.If the interval is set after the Timer has started, the count is reset. Например, если задать для интервала значение 5 секунд, а затем задать Enabled для свойства значение true , счетчик начнется в Enabled заданное время.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. Если интервал равен 10 секундам при значении счетчика 3 секунды, Elapsed событие будет вызвано в первый раз за 13 секунд после Enabled установки значения 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.

Примечание

Некоторые визуальные конструкторы, например, в Microsoft Visual Studio, устанавливают Enabled свойство в значение true при вставке нового Timer .Some visual designers, such as those in Microsoft Visual Studio, set the Enabled property to true when inserting a new Timer.

Применяется к

См. также раздел