CodeLiturgy.Dashboard/BlueWest/Core/TimeSystem/TimerTick.cs

84 lines
2.3 KiB
C#

using System;
using System.Diagnostics;
namespace BlueWest.Core
{
public class TimerTick
{
private long startRawTime;
private long lastRawTime;
private int pauseCount;
private long pauseStartTime;
private long timePaused;
private static decimal speedFactor = 1.0m;
public TimeSpan StartTime { get; private set; }
public TimeSpan TotalTime { get; private set; }
public TimeSpan TotalTimeWithPause { get; private set; }
public TimeSpan ElapsedTime { get; private set; }
public TimeSpan ElapsedTimeWithPause { get; private set; }
public void Reset()
{
Reset(TimeSpan.Zero);
}
public void Reset(TimeSpan startTime)
{
StartTime = startTime;
TotalTime = startTime;
startRawTime = Stopwatch.GetTimestamp();
lastRawTime = startRawTime;
timePaused = 0;
pauseStartTime = 0;
pauseCount = 0;
}
public void Resume()
{
pauseCount--;
if (pauseCount <= 0)
{
timePaused += Stopwatch.GetTimestamp() - pauseStartTime;
pauseStartTime = 0L;
}
}
public void Tick()
{
var rawTime = Stopwatch.GetTimestamp();
TotalTime = StartTime + new TimeSpan((long)Math.Round(ConvertRawToTimestamp(rawTime - timePaused - startRawTime).Ticks * speedFactor));
TotalTimeWithPause = StartTime + new TimeSpan((long)Math.Round(ConvertRawToTimestamp(rawTime - startRawTime).Ticks * speedFactor));
ElapsedTime = ConvertRawToTimestamp(rawTime - timePaused - lastRawTime);
ElapsedTimeWithPause = ConvertRawToTimestamp(rawTime - lastRawTime);
if (ElapsedTime < TimeSpan.Zero)
{
ElapsedTime = TimeSpan.Zero;
}
lastRawTime = rawTime;
}
public TimeSpan ConvertRawToTimestamp(long delta)
{
return new TimeSpan(delta == 0 ? 0 : (delta * TimeSpan.TicksPerSecond) / Stopwatch.Frequency);
}
public void Pause()
{
pauseCount++;
if (pauseCount == 1)
{
pauseStartTime = Stopwatch.GetTimestamp();
}
}
}
}