This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
forked from dotnet/dotNext
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AsyncTimer.cs
266 lines (239 loc) · 10.6 KB
/
AsyncTimer.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace DotNext.Threading
{
using FalseTask = Tasks.CompletedTask<bool, Generic.BooleanConst.False>;
/// <summary>
/// Represents asynchronous timer.
/// </summary>
/// <remarks>
/// This timer provides guarantees than two executions of timer callback cannot be overlapped, i.e. executed twice or more concurrently at the same time.
/// </remarks>
public class AsyncTimer : Disposable, IAsyncDisposable
{
private sealed class TimerCompletionSource : TaskCompletionSource<bool>, IDisposable
{
private const byte BeginInitState = 0;
private const byte EndInitState = 1;
private const byte BeginLoopState = 2;
private const byte EndLoopState = 3;
private const byte BeginDelayState = 4;
private const byte EndDelayState = 5;
private readonly CancellationTokenSource cancellation;
private readonly TimeSpan dueTime, period;
private readonly Func<CancellationToken, Task<bool>> callback;
// state management
private readonly Action continuation;
private byte state;
private ConfiguredTaskAwaitable.ConfiguredTaskAwaiter voidAwaiter;
private ConfiguredTaskAwaitable<bool>.ConfiguredTaskAwaiter boolAwaiter;
internal TimerCompletionSource(TimeSpan dueTime, TimeSpan period, Func<CancellationToken, Task<bool>> callback, CancellationToken token)
{
cancellation = CancellationTokenSource.CreateLinkedTokenSource(token);
this.dueTime = dueTime;
this.period = period;
this.callback = callback;
continuation = Execute;
}
internal void RequestCancellation() => cancellation.Cancel();
private void Execute()
{
try
{
switch (state)
{
case BeginInitState:
voidAwaiter = System.Threading.Tasks.Task.Delay(dueTime, cancellation.Token).ConfigureAwait(false).GetAwaiter();
if (voidAwaiter.IsCompleted)
goto case EndInitState;
state = EndInitState;
voidAwaiter.OnCompleted(continuation);
break;
case EndInitState:
voidAwaiter.GetResult();
voidAwaiter = default;
goto case BeginLoopState;
case BeginLoopState:
boolAwaiter = callback.Invoke(cancellation.Token).ConfigureAwait(false).GetAwaiter();
if (boolAwaiter.IsCompleted)
goto case EndLoopState;
state = EndLoopState;
boolAwaiter.OnCompleted(continuation);
break;
case EndLoopState:
var success = boolAwaiter.GetResult();
boolAwaiter = default;
if (success)
goto case BeginDelayState;
TrySetResult(true);
break;
case BeginDelayState:
voidAwaiter = System.Threading.Tasks.Task.Delay(period, cancellation.Token).ConfigureAwait(false).GetAwaiter();
if (voidAwaiter.IsCompleted)
goto case EndDelayState;
state = EndDelayState;
voidAwaiter.OnCompleted(continuation);
break;
case EndDelayState:
voidAwaiter.GetResult();
voidAwaiter = default;
goto case BeginLoopState;
}
}
catch (OperationCanceledException)
{
TrySetResult(false);
}
catch (Exception e)
{
TrySetException(e);
}
if (Task.IsCompleted)
cancellation.Dispose();
}
internal void Start()
{
ThreadPool.QueueUserWorkItem(Start, this, false);
static void Start(TimerCompletionSource source) => source.Execute();
}
private void Dispose(bool disposing)
{
if (disposing)
{
cancellation.Dispose();
voidAwaiter = default;
boolAwaiter = default;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~TimerCompletionSource() => Dispose(false);
}
private readonly Func<CancellationToken, Task<bool>> callback;
[SuppressMessage("Usage", "CA2213", Justification = "Disposed correctly but cannot be recognized by .NET Analyzer")]
private volatile TimerCompletionSource? timerTask;
private bool disposeRequested;
/// <summary>
/// Initializes a new timer.
/// </summary>
/// <param name="callback">The timer callback.</param>
/// <exception cref="ArgumentNullException"><paramref name="callback"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="callback"/> doesn't refer to any method.</exception>
public AsyncTimer(Func<CancellationToken, Task<bool>> callback)
{
this.callback = callback ?? throw new ArgumentException(ExceptionMessages.EmptyValueDelegate, nameof(callback));
}
/// <summary>
/// Indicates that this timer is running.
/// </summary>
public bool IsRunning
{
get
{
var task = timerTask;
return task is not null && !task.Task.IsCompleted;
}
}
/// <summary>
/// Starts the timer.
/// </summary>
/// <param name="dueTime">The amount of time to delay before the invoking the timer callback.</param>
/// <param name="period">The time interval between invocations of the timer callback.</param>
/// <param name="token">The token that can be used to stop execution of the timer.</param>
/// <returns><see langword="true"/> if timer was in stopped state; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ObjectDisposedException">The timer has been disposed.</exception>
/// <exception cref="OperationCanceledException"><paramref name="token"/> is in canceled state.</exception>
[MethodImpl(MethodImplOptions.Synchronized)]
public bool Start(TimeSpan dueTime, TimeSpan period, CancellationToken token = default)
{
ThrowIfDisposed();
token.ThrowIfCancellationRequested();
if ((timerTask is null || timerTask.Task.IsCompleted) && !disposeRequested)
{
var source = new TimerCompletionSource(dueTime, period, callback, token);
source.Start();
timerTask = source;
return true;
}
return false;
}
/// <summary>
/// Starts the timer.
/// </summary>
/// <param name="period">The time interval between invocations of the timer callback.</param>
/// <param name="token">The token that can be used to stop execution of the timer.</param>
/// <returns><see langword="true"/> if timer was in stopped state; otherwise, <see langword="false"/>.</returns>
public bool Start(TimeSpan period, CancellationToken token = default)
=> Start(period, period, token);
/// <summary>
/// Stops timer execution.
/// </summary>
/// <returns><see langword="true"/> if timer shutdown was initiated by the callback; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ObjectDisposedException">The timer has been disposed.</exception>
[MethodImpl(MethodImplOptions.Synchronized)]
public Task<bool> StopAsync()
{
if (IsDisposed)
return GetDisposedTask<bool>();
var result = timerTask;
if (result is null || result.Task.IsCompleted)
return FalseTask.Task;
result.RequestCancellation();
return result.Task;
}
/// <summary>
/// Releases all resources associated with this timer.
/// </summary>
/// <param name="disposing"><see langword="true"/> if called from <see cref="Disposable.Dispose()"/>; <see langword="false"/> if called from finalizer <see cref="Disposable.Finalize()"/>.</param>
protected override void Dispose(bool disposing)
{
disposeRequested = true;
if (disposing)
{
var timerTask = Interlocked.Exchange(ref this.timerTask, null);
if (timerTask is not null)
{
TrySetDisposedException(timerTask);
timerTask.Dispose();
}
}
base.Dispose(disposing);
}
private void Dispose(Task parent, object? state)
{
(state as IDisposable)?.Dispose();
Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
private Task DisposeAsyncImpl()
{
var result = Interlocked.Exchange(ref timerTask, null);
if (result is null)
{
}
else if (result.Task.IsCompleted)
{
result.Dispose();
}
else
{
disposeRequested = true;
result.RequestCancellation();
return result.Task.ContinueWith(Dispose, result, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);
}
Dispose();
return Task.CompletedTask;
}
/// <summary>
/// Terminates timer gracefully.
/// </summary>
/// <returns>The task representing graceful shutdown.</returns>
public ValueTask DisposeAsync() => new(IsDisposed ? Task.CompletedTask : DisposeAsyncImpl());
}
}