-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClock.cs
More file actions
60 lines (50 loc) · 1.58 KB
/
Copy pathClock.cs
File metadata and controls
60 lines (50 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Chip8
{
public class Clock
{
// = (TimeSpan.TicksPerSecond / 500)
const int ticksPer500Hz = 20_000;
// = (TimeSpan.TicksPerSecond / 60)
const int ticksPer60Hz = 166_666;
private readonly Task thread;
private readonly Action tick60Hz;
private readonly Action tick500Hz;
private readonly Stopwatch stopwatch;
private long last60Hz = 0;
private long last500Hz = 0;
public Clock(Action tick60Hz, Action tick500Hz, bool running = true)
{
stopwatch = Stopwatch.StartNew();
this.tick60Hz = tick60Hz;
this.tick500Hz = tick500Hz;
Running = running;
thread = Task.Run(Loop);
}
public bool Running { get; set; }
private void Loop()
{
while (true)
{
if (stopwatch.ElapsedTicks - last500Hz > ticksPer500Hz)
{
last500Hz = stopwatch.ElapsedTicks;
if (Running)
{
tick500Hz();
}
}
if (stopwatch.ElapsedTicks - last60Hz > ticksPer60Hz)
{
last60Hz = stopwatch.ElapsedTicks;
tick60Hz();
}
var sleepFor = TimeSpan.FromTicks(Math.Min(0, stopwatch.ElapsedTicks - last500Hz));
Thread.Sleep(sleepFor);
}
}
}
}