forked from Dasync/AsyncEnumerable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncEnumerator.cs
232 lines (206 loc) · 8.1 KB
/
AsyncEnumerator.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
using System.Threading;
using System.Threading.Tasks;
namespace System.Collections.Async
{
/// <summary>
/// Helps to enumerate items in a collection asynchronously
/// </summary>
public sealed class AsyncEnumerator<T> : IAsyncEnumerator<T>
{
/// <summary>
/// This exception is thrown when you call <see cref="Yield.Break"/>
/// </summary>
public sealed class AsyncEnumerationCanceledException : OperationCanceledException { }
/// <summary>
/// The asynchronous version of the 'yield' construction
/// </summary>
public sealed class Yield
{
private TaskCompletionSource<bool> _resumeTCS;
private TaskCompletionSource<T> _yieldTCS;
/// <summary>
/// Gets the cancellation token that was passed to the <see cref="MoveNextAsync"/> method
/// </summary>
public CancellationToken CancellationToken { get; private set; }
/// <summary>
/// Yields an item asynchronously (similar to 'yield return' statement)
/// </summary>
/// <param name="item">The item of the collection to yield</param>
/// <returns>Returns a Task which tells if when you can continue to yield the next item</returns>
public Task ReturnAsync(T item)
{
_resumeTCS = new TaskCompletionSource<bool>();
_yieldTCS.TrySetResult(item);
return _resumeTCS.Task;
}
/// <summary>
/// Stops iterating items in the collection (similar to 'yield break' statement)
/// </summary>
/// <exception cref="AsyncEnumerationCanceledException">Always throws this exception to stop the enumeration task</exception>
public void Break()
{
SetCanceled();
throw new AsyncEnumerationCanceledException();
}
internal void SetComplete()
{
_yieldTCS.TrySetCanceled();
IsComplete = true;
}
internal void SetCanceled()
{
SetComplete();
}
internal void SetFailed(Exception ex)
{
_yieldTCS.TrySetException(ex);
IsComplete = true;
}
internal Task<T> OnMoveNext(CancellationToken cancellationToken)
{
if (!IsComplete) {
_yieldTCS = new TaskCompletionSource<T>();
CancellationToken = cancellationToken;
if (_resumeTCS != null)
_resumeTCS.SetResult(true);
}
return _yieldTCS.Task;
}
internal void Finilize()
{
SetCanceled();
}
internal bool IsComplete { get; set; }
}
private Func<Yield, Task> _enumerationFunction;
private bool _oneTimeUse;
private Yield _yield;
private T _current;
private Task _enumerationTask;
private Exception _enumerationException;
/// <summary>
/// Constructor
/// </summary>
/// <param name="enumerationFunction">A function that enumerates items in a collection asynchronously</param>
public AsyncEnumerator(Func<Yield, Task> enumerationFunction)
: this(enumerationFunction, oneTimeUse: false)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="enumerationFunction">A function that enumerates items in a collection asynchronously</param>
/// <param name="oneTimeUse">When True the enumeration can be performed once only and Reset method is not allowed</param>
public AsyncEnumerator(Func<Yield, Task> enumerationFunction, bool oneTimeUse)
{
_enumerationFunction = enumerationFunction;
_oneTimeUse = oneTimeUse;
ClearState();
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator
/// </summary>
public T Current
{
get
{
if (_enumerationTask == null)
throw new InvalidOperationException("Call MoveNext() or MoveNextAsync() before accessing the Current item");
return _current;
}
private set
{
_current = value;
}
}
object IEnumerator.Current => Current;
/// <summary>
/// Advances the enumerator to the next element of the collection asynchronously
/// </summary>
/// <param name="cancellationToken">A cancellation token to cancel the enumeration</param>
/// <returns>Returns a Task that does transition to the next element. The result of the task is True if the enumerator was successfully advanced to the next element, or False if the enumerator has passed the end of the collection.</returns>
public Task<bool> MoveNextAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_enumerationException != null) {
var tcs = new TaskCompletionSource<bool>();
tcs.SetException(_enumerationException);
return tcs.Task;
}
var moveNextTask = _yield.OnMoveNext(cancellationToken).ContinueWith(OnMoveNextComplete, _yield);
if (_enumerationTask == null)
_enumerationTask = _enumerationFunction(_yield).ContinueWith(OnEnumerationComplete, _yield);
return moveNextTask;
}
/// <summary>
/// Advances the enumerator to the next element of the collection
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
return MoveNextAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Sets the enumerator to its initial position asynchronously, which is before the first element in the collection
/// </summary>
public Task ResetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
Reset();
return Task.FromResult<object>(null);
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection
/// </summary>
public void Reset()
{
if (_oneTimeUse)
throw new InvalidOperationException("The enumeration can be performed once only");
ClearState();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources
/// </summary>
public void Dispose()
{
ClearState();
}
private void ClearState()
{
if (_yield != null)
_yield.Finilize();
_yield = new Yield();
_enumerationTask = null;
_enumerationException = null;
}
private bool OnMoveNextComplete(Task<T> task, object state)
{
var yield = (Yield)state;
if (yield.IsComplete) {
return false;
}
if (task.IsFaulted) {
_enumerationException = task.Exception;
throw _enumerationException;
} else if (task.IsCanceled) {
return false;
} else {
Current = task.Result;
return true;
}
}
private static void OnEnumerationComplete(Task task, object state)
{
var yield = (Yield)state;
if (task.IsFaulted) {
if (task.Exception is AsyncEnumerationCanceledException) {
yield.SetCanceled();
} else {
yield.SetFailed(task.Exception);
}
} else if (task.IsCanceled) {
yield.SetCanceled();
} else {
yield.SetComplete();
}
}
}
}