-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTimer.cs
47 lines (38 loc) · 872 Bytes
/
Timer.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
using System.Threading;
namespace BatteryTracker.Helpers;
class Timer
{
public Action? Action { get; set; }
System.Threading.Timer? _timer;
int _interval; // in milliseconds
bool _continue = true;
public async void StartTimer(int interval)
{
_continue = true;
_interval = interval;
if (_timer != null)
{
await _timer.DisposeAsync();
}
_timer = new System.Threading.Timer(Tick, null, interval, Timeout.Infinite);
}
public void StopTimer() => _continue = false;
void Tick(object state)
{
try
{
Action?.Invoke();
}
finally
{
if (_continue)
{
_timer?.Change(_interval, Timeout.Infinite);
}
}
}
~Timer()
{
_timer?.Dispose();
}
}