如何暂停C#计时器?

20
我有一个C#程序,在其中,如果用户停止与程序交互,我需要定时器停止。它需要暂停,然后在用户再次活动时重新启动。我做了一些研究,发现有诸如以下命令:
timer.Stop(); 

timer.Start();

但是我想知道是否有这样一个:

timer.Pause();

当用户再次活动时,应用程序会从离开的地方继续执行,而不是重新启动。如果有人能够帮忙,将不胜感激!

Micah


3
你使用的是哪个 Timer 类?为什么 Stop() 方法不能满足你的需求?你不能稍后再调用 Start() 吗? - Peter Duniho
正如其他人和示例解决方案所指出的,停止/暂停计时器是不明确的,除非我们知道您要暂停和恢复什么上下文。依赖于先前步骤结果的复杂计算、查询数据库、监测传感器和网络等。 - DRapp
3个回答

26

您可以通过在.NET中使用Stopwatch类来实现此目的。仅需停止和启动即可继续使用秒表实例。

请确保使用using System.Diagnostics;

var timer = new Stopwatch();
timer.Start();
timer.Stop();
Console.WriteLine(timer.Elapsed);

timer.Start(); //Continues the timer from the previously stopped time
timer.Stop();
Console.WriteLine(timer.Elapsed);

要重置秒表,只需调用ResetRestart方法,如下所示:

timer.Reset();
timer.Restart();

请问您能否解释一下为什么这个答案被踩了? - Prabu
1
我也不知道,但问题是关于用户活动<->不活动的。给提问者的提示:使用两个计时器并没有什么可耻的。 - TaW
“Reset”和“Restart”之间有什么区别吗? - Black
我需要计时器,因为它有tick事件,但是秒表没有tick事件。 - Ramil Aliyev 007
1
@Black,如果你还在犹豫的话 ;) Reset 停止并重置计时器;Restart 也是一样,但它还会启动被重置的秒表。 - Stefan

8
我为这种情况创建了这个类:
public class PausableTimer : Timer
{
    public double RemainingAfterPause { get; private set; }

    private readonly Stopwatch _stopwatch;
    private readonly double _initialInterval;
    private bool _resumed;

    public PausableTimer(double interval) : base(interval)
    {
        _initialInterval = interval;
        Elapsed += OnElapsed;
        _stopwatch = new Stopwatch();
    }

    public new void Start()
    {
        ResetStopwatch();
        base.Start();
    }

    private void OnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        if (_resumed)
        {
            _resumed = false;
            Stop();
            Interval = _initialInterval;
            Start();
        }

        ResetStopwatch();
    }

    private void ResetStopwatch()
    {
        _stopwatch.Reset();
        _stopwatch.Start();
    }

    public void Pause()
    {
        Stop();
        _stopwatch.Stop();
        RemainingAfterPause = Interval - _stopwatch.Elapsed.TotalMilliseconds;
    }

    public void Resume()
    {
        _resumed = true;
        Interval = RemainingAfterPause;
        RemainingAfterPause = 0;
        Start();
    }

}

4
没有暂停是因为它很容易实现同等效果。你可以停止计时器而不是暂停它,然后当你需要重新启动时,只需指定剩余时间即可。这可能有些复杂,也可能很简单;这取决于你使用计时器做什么。你所做的取决于你使用计时器的目的,这可能是暂停不存在的原因。
你可能在定期时间内重复执行某项任务,也可能在倒计时到达特定时间时使用计时器。如果你正在重复执行某些任务(如每秒钟),那么你的要求可能是在该时间段(一秒钟)的开始或部分重新启动。如果暂停超过了时间周期会发生什么?通常错过的事件将被忽略,但这取决于要求。
因此,我想说的是你需要确定你的要求。如果你需要帮助,请澄清你需要什么。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接