C#如何暂停计时器?

Mic*_*tal 12 c#

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

timer.Stop(); 
Run Code Online (Sandbox Code Playgroud)

timer.Start();
Run Code Online (Sandbox Code Playgroud)

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

timer.Pause();
Run Code Online (Sandbox Code Playgroud)

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

米卡

Pra*_*abu 15

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

一定要好好利用 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);
Run Code Online (Sandbox Code Playgroud)

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

timer.Reset();
timer.Restart();
Run Code Online (Sandbox Code Playgroud)


And*_*rew 5

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

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

}
Run Code Online (Sandbox Code Playgroud)