如何在预定义时间后暂停Timer_Tick

本文关键字:暂停 Timer Tick 时间 预定义 | 更新日期: 2023-09-27 18:28:10

我正在开发一个web应用程序。在这个应用程序中,我想在12分钟后暂停计时器。我怎么能这么做?或者,我在哪里可以指定该时间,以便暂停计时器滴答声?

如何在预定义时间后暂停Timer_Tick

您可以使用回调中的状态对象来获取计时器实例
然后,如果您想停止计时器,可以在回调内部进行检查
您可以简单地计算刻度的数量,并计算每个刻度中经过的时间:

    ...
    // Start the timer
    // you have to use this constructor if you want to
    // access the timer itself inside callback
    var timer = new Timer(Callback);
    timer.Change(100, period);
}
// Set desired period
private static int period = 100;
// Track elapsed time
private static int elapsed;
private static void Callback(object state)
{
    // update elapsed time
    ellapsed += period;
    // check if ellapsed is greater than 12min
    bool isElapsed = ellapsed >= 12 * 60 * 1000;
    if (!isElapsed) return;
    var timer = state as Timer;
    if ( timer != null)
        timer.Change(Timeout.Infinite, Timeout.Infinite);
}