Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to pause a timer?

Tags:

c#

I have a C# program in which, I need the timer to stop if the user stops interacting with the program. What It needs to do is pause, and then restart when the user becomes active again. I have done some research, and found that there is commands such as:

timer.Stop(); 

and

timer.Start();

But I was wondering if there was like a:

timer.Pause();

And then when the user becomes active again, it picks up where it left off, and doesn't restart. If anyone can help, it would be much appreciated! Thanks,

Micah

like image 981
Micah Vertal Avatar asked Nov 17 '14 01:11

Micah Vertal


2 Answers

You achieve this by using the Stopwatch class in .NET. By simply stopping and starting you continue the use of the instance of the stopwatch.

Make sure to make use of 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);

To reset the stopwatch, just call the Reset or Restart methods, like below:

timer.Reset();
timer.Restart();
like image 121
Prabu Avatar answered Sep 17 '22 20:09

Prabu


I have created this class for this situation:

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

}
like image 23
Andrew Avatar answered Sep 18 '22 20:09

Andrew