Click here to Skip to main content
15,867,906 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,

I have a windows application in which I have to display the 'Remaining Time'.

Now, I have a requirement to stop/resume the 'Remaining Time'.

What I have tried:

//REMAIN TIME CODE
public TimeSpan RemainingTime
        {
            get
            {
                _elapsedTime = DateTime.Now - StartTime;
                TimeSpan remainingTime = Duration - _elapsedTime;

                if (remainingTime > TimeSpan.Zero)
                    return remainingTime;
                else
                    return TimeSpan.Zero;
            }
        }


Here, the problem is, I'm using DateTime.Now to calculate the remaining, so, I'm not able to stop/resume the remaining time. Even though I'm using timerTick_Event.

Can anyone please help me.


Thanks
Posted
Updated 9-May-19 14:18pm

If you use a start time and Now to calculate the "run time so far" (which is the right way, Tick events aren't real time, so they "drift" if you assume they are accurate) then the only way to "Pause the timer" is to store the elapsed time when you hit "pause" and recalculate the "start time" when you unpause, based on the current time at that point.
Pause:
   elapsedTime = DateTime.Now - StartTime;
   paused = true;

C#
UnPause:
   StartTime = DateTime.Now - elapsedTime;
   paused = false;
 
Share this answer
 
Rather than using DateTime.Now to measure the elapsed time, use the Stopwatch class[^].
C#
private Stopwatch _timer;

public void Start()
{
    _timer = Stopwatch.StartNew();
}

public void Pause()
{
    if (_timer is null) throw new InvalidOperationException();
    if (_timer.IsRunning) _timer.Stop();
}

public void Resume()
{
    if (_timer is null) throw new InvalidOperationException();
    if (!_timer.IsRunning) _timer.Start();
}

public TimeSpan RemainingTime
{
    get
    {
        if (_timer is null) return TimeSpan.MaxValue;
        
        TimeSpan remainingTime = Duration - _timer.Elapsed;
        return remainingTime > TimeSpan.Zero ? remainingTime : TimeSpan.Zero;
    }
}
 
Share this answer
 
Quote:
Now, I have a requirement to stop/resume the 'Remaining Time'.

Rather simple, add an OffsetTime variable to your code.
for elapsed time:
on start, OffsetTime = 0
on run, ElapsedTime = DateTime.Now - StartTime + OffsetTime
on stop, OffsetTime = DateTime.Now - StartTime + OffsetTime
when stopped, ElapsedTime = OffsetTime
for CountDown:
on start, just set OffsetTime to remaining time
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900