-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathManualUpdateTrigger.cs
96 lines (77 loc) · 2.48 KB
/
ManualUpdateTrigger.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// ReSharper disable MemberCanBePrivate.Global
using System.Threading;
using System.Threading.Tasks;
namespace RGB.NET.Core;
/// <inheritdoc />
/// <summary>
/// Represents an update trigger that is manully triggered by calling <see cref="TriggerUpdate"/>.
/// </summary>
public sealed class ManualUpdateTrigger : AbstractUpdateTrigger
{
#region Properties & Fields
private readonly AutoResetEvent _mutex = new(false);
private Task? UpdateTask { get; set; }
private CancellationTokenSource? UpdateTokenSource { get; set; }
private CancellationToken UpdateToken { get; set; }
private CustomUpdateData? _customUpdateData;
/// <summary>
/// Gets the time it took the last update-loop cycle to run.
/// </summary>
public override double LastUpdateTime { get; protected set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ManualUpdateTrigger"/> class.
/// </summary>
public ManualUpdateTrigger()
{
Start();
}
#endregion
#region Methods
/// <summary>
/// Starts the trigger if needed, causing it to performing updates.
/// </summary>
public override void Start()
{
if (UpdateTask == null)
{
UpdateTokenSource?.Dispose();
UpdateTokenSource = new CancellationTokenSource();
UpdateTask = Task.Factory.StartNew(UpdateLoop, (UpdateToken = UpdateTokenSource.Token), TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
/// <summary>
/// Stops the trigger if running, causing it to stop performing updates.
/// </summary>
private void Stop()
{
if (UpdateTask != null)
{
UpdateTokenSource?.Cancel();
// ReSharper disable once MethodSupportsCancellation
UpdateTask.Wait();
UpdateTask.Dispose();
UpdateTask = null;
}
}
/// <summary>
/// Triggers an update.
/// </summary>
public void TriggerUpdate(CustomUpdateData? updateData = null)
{
_customUpdateData = updateData;
_mutex.Set();
}
private void UpdateLoop()
{
OnStartup();
while (!UpdateToken.IsCancellationRequested)
if (_mutex.WaitOne(100))
LastUpdateTime = TimerHelper.Execute(TimerExecute);
}
private void TimerExecute() => OnUpdate(_customUpdateData);
/// <inheritdoc />
public override void Dispose() => Stop();
#endregion
}