繁体   English   中英

C#如何暂停计时器?

[英]C# How to pause a timer?

我有一个C#程序,如果用户停止与程序交互,我需要停止计时器。 它需要做的是暂停,然后在用户再次激活时重新启动。 我做了一些研究,发现有以下命令:

timer.Stop(); 

timer.Start();

但我想知道是否有这样的:

timer.Pause();

然后当用户再次变为活动状态时,它会从中断处继续,并且不会重新启动。 如果有人可以提供帮助,我们将不胜感激! 谢谢,

米卡

您可以通过在.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();

没有暂停因为很容易做同等的事情。 您只需停止计时器而不是暂停计时器,然后当您需要重新启动它时,您只需指定剩余的时间量。 它可能很复杂,也可能很简单; 这取决于你使用计时器做什么。 您所做的事情取决于您使用计时器的原因可能是暂停不存在的原因。

您可能正在使用计时器在常规时间段内重复执行某些操作,或者您可能正在使用计时器倒计时到特定时间。 如果您正在重复执行某些操作(例如每秒),那么您的要求可能是在该时间段的开始(一秒)或该时段的一部分重新启动。 如果暂停超过时间段会发生什么? 通常会忽略错过的事件,但这取决于要求。

所以我想说你需要确定你的要求。 然后,如果您需要帮助,请说明您的需求。

我为这种情况创建了这个类:

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();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM