-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeepAliveTimer.cs
60 lines (54 loc) · 1.53 KB
/
KeepAliveTimer.cs
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.Windows.Threading;
namespace ZoomAndPan
{
public class KeepAliveTimer
{
private readonly DispatcherTimer _timer;
private DateTime _startTime;
private TimeSpan? _runTime;
public TimeSpan Time { get; set; }
public Action Action { get; set; }
public bool Running { get; private set; }
public KeepAliveTimer(TimeSpan time, Action action)
{
Time = time;
Action = action;
_timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = time };
_timer.Tick += TimerExpired;
}
private void TimerExpired(object sender, EventArgs e)
{
lock (_timer)
{
Running = false;
_timer.Stop();
_runTime = DateTime.UtcNow.Subtract(_startTime);
Action();
}
}
public void Nudge()
{
lock (_timer)
{
if (!Running)
{
_startTime = DateTime.UtcNow;
_runTime = null;
_timer.Start();
Running = true;
}
else
{
//Reset the timer
_timer.Stop();
_timer.Start();
}
}
}
public TimeSpan GetTimeSpan()
{
return _runTime ?? DateTime.UtcNow.Subtract(_startTime);
}
}
}