使用英语阅读

通过


Timer.Enabled 属性

定义

获取或设置一个值,该值指示 Timer 是否应引发 Elapsed 事件。

C#
public bool Enabled { get; set; }
C#
[System.Timers.TimersDescription("TimerEnabled")]
public bool Enabled { get; set; }

属性值

如果 Timer 应引发 Elapsed 事件,则为 true;否则,为 false。 默认值为 false

属性

例外

计时器已释放,无法设置此属性。

在启用计时器之前,属性 Interval 设置为大于 Int32.MaxValue 的值。

示例

以下示例实例化一个 Timer 对象,该对象每两秒 (2000 毫秒) 触发一 Timer.Elapsed 次事件,为事件设置事件处理程序,并启动计时器。 每次引发属性时, ElapsedEventArgs.SignalTime 事件处理程序都会显示该属性的值。

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

注解

将 设置为 Enabled 与调用 Start相同,而设置为 Enabledfalse 与调用 Stop相同。true

备注

引发 Elapsed 事件的信号始终在线程上 ThreadPool 排队等待执行。 这可能会导致 在 Elapsed 属性设置为 falseEnabled引发 事件。 方法的 Stop 代码示例演示了解决此争用条件的一种方法。

如果 Enabled 设置为 true ,并且 AutoReset 设置为 false,则 Timer 仅引发 Elapsed 一次事件,即间隔过后的第一次。

如果间隔是在 启动后 Timer 设置的,则计数将重置。 例如,如果将间隔设置为 5 秒,然后将 属性设置为 Enabledtrue,则在设置时 Enabled 开始计数。 如果在 count 为 3 秒时将间隔重置为 10 秒,则会Elapsed在设置为 trueEnabled 13 秒首次引发事件。

备注

某些视觉设计器(例如 Microsoft Visual Studio 中的设计器)在插入新的 Timer时将 true 属性设置为 Enabled

适用于

产品 版本
.NET 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 2.0, 2.1

另请参阅