-
-
Notifications
You must be signed in to change notification settings - Fork 358
/
AsyncCollection.cs
310 lines (271 loc) · 14.8 KB
/
AsyncCollection.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Nito.AsyncEx.Synchronous;
namespace Nito.AsyncEx
{
/// <summary>
/// An async-compatible producer/consumer collection.
/// </summary>
/// <typeparam name="T">The type of elements contained in the collection.</typeparam>
[DebuggerDisplay("Count = {_collection.Count}, MaxCount = {_maxCount}")]
[DebuggerTypeProxy(typeof(AsyncCollection<>.DebugView))]
public sealed class AsyncCollection<T>
{
/// <summary>
/// The underlying collection.
/// </summary>
private readonly IProducerConsumerCollection<T> _collection;
/// <summary>
/// The maximum number of elements allowed in the collection.
/// </summary>
private readonly int _maxCount;
/// <summary>
/// The mutual-exclusion lock protecting the collection.
/// </summary>
private readonly AsyncLock _mutex;
/// <summary>
/// A condition variable that is signalled when the collection is completed or not full.
/// </summary>
private readonly AsyncConditionVariable _completedOrNotFull;
/// <summary>
/// A condition variable that is signalled when the collection is completed or not empty.
/// </summary>
private readonly AsyncConditionVariable _completedOrNotEmpty;
/// <summary>
/// Whether the collection has been marked completed for adding.
/// </summary>
private bool _completed;
/// <summary>
/// Creates a new async-compatible producer/consumer collection wrapping the specified collection and with a maximum element count.
/// </summary>
/// <param name="collection">The collection to wrap.</param>
/// <param name="maxCount">The maximum element count. This must be greater than zero.</param>
public AsyncCollection(IProducerConsumerCollection<T>? collection, int maxCount)
{
collection ??= new ConcurrentQueue<T>();
if (maxCount <= 0)
throw new ArgumentOutOfRangeException(nameof(maxCount), "The maximum count must be greater than zero.");
if (maxCount < collection.Count)
throw new ArgumentException("The maximum count cannot be less than the number of elements in the collection.", nameof(maxCount));
_collection = collection;
_maxCount = maxCount;
_mutex = new AsyncLock();
_completedOrNotFull = new AsyncConditionVariable(_mutex);
_completedOrNotEmpty = new AsyncConditionVariable(_mutex);
}
/// <summary>
/// Creates a new async-compatible producer/consumer collection wrapping the specified collection.
/// </summary>
/// <param name="collection">The collection to wrap.</param>
public AsyncCollection(IProducerConsumerCollection<T>? collection)
: this(collection, int.MaxValue)
{
}
/// <summary>
/// Creates a new async-compatible producer/consumer collection with a maximum element count.
/// </summary>
/// <param name="maxCount">The maximum element count. This must be greater than zero.</param>
public AsyncCollection(int maxCount)
: this(null, maxCount)
{
}
/// <summary>
/// Creates a new async-compatible producer/consumer collection.
/// </summary>
public AsyncCollection()
: this(null, int.MaxValue)
{
}
/// <summary>
/// Whether the collection is empty.
/// </summary>
private bool Empty => _collection.Count == 0;
/// <summary>
/// Whether the collection is full.
/// </summary>
private bool Full => _collection.Count == _maxCount;
/// <summary>
/// Synchronously marks the producer/consumer collection as complete for adding.
/// </summary>
public void CompleteAdding()
{
using (_mutex.Lock())
{
_completed = true;
_completedOrNotEmpty.NotifyAll();
_completedOrNotFull.NotifyAll();
}
}
/// <summary>
/// Attempts to add an item.
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param>
/// <param name="sync">Whether to run this method synchronously.</param>
internal async Task DoAddAsync(T item, CancellationToken cancellationToken, bool sync)
{
using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false))
{
// Wait for the collection to be not full.
while (Full && !_completed)
{
if (sync)
_completedOrNotFull.Wait(cancellationToken);
else
await _completedOrNotFull.WaitAsync(cancellationToken).ConfigureAwait(false);
}
// If the queue has been marked complete, then abort.
if (_completed)
throw new InvalidOperationException("Add failed; the producer/consumer collection has completed adding.");
if (!_collection.TryAdd(item))
throw new InvalidOperationException("Add failed; the add to the underlying collection failed.");
_completedOrNotEmpty.Notify();
}
}
/// <summary>
/// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection.
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param>
public Task AddAsync(T item, CancellationToken cancellationToken) => DoAddAsync(item, cancellationToken, sync: false);
/// <summary>
/// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread.
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param>
public void Add(T item, CancellationToken cancellationToken) => DoAddAsync(item, cancellationToken, sync: true).WaitAndUnwrapException(CancellationToken.None);
/// <summary>
/// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection.
/// </summary>
/// <param name="item">The item to add.</param>
public Task AddAsync(T item) => AddAsync(item, CancellationToken.None);
/// <summary>
/// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(T item) => Add(item, CancellationToken.None);
/// <summary>
/// Waits until an item is available to take. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the wait.</param>
/// <param name="sync">Whether to run this method synchronously.</param>
private async Task<bool> DoOutputAvailableAsync(CancellationToken cancellationToken, bool sync)
{
using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false))
{
while (Empty && !_completed)
{
if (sync)
_completedOrNotEmpty.Wait(cancellationToken);
else
await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false);
}
return !Empty;
}
}
/// <summary>
/// Asynchronously waits until an item is available to take. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the asynchronous wait.</param>
public Task<bool> OutputAvailableAsync(CancellationToken cancellationToken) => DoOutputAvailableAsync(cancellationToken, sync: false);
/// <summary>
/// Asynchronously waits until an item is available to take. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items.
/// </summary>
public Task<bool> OutputAvailableAsync() => OutputAvailableAsync(CancellationToken.None);
/// <summary>
/// Synchronously waits until an item is available to take. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the wait.</param>
public bool OutputAvailable(CancellationToken cancellationToken) => DoOutputAvailableAsync(cancellationToken, sync: true).WaitAndUnwrapException();
/// <summary>
/// Synchronously waits until an item is available to take. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items.
/// </summary>
public bool OutputAvailable() => OutputAvailable(CancellationToken.None);
/// <summary>
/// Provides a (synchronous) consuming enumerable for items in the producer/consumer collection.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the synchronous enumeration.</param>
public IEnumerable<T> GetConsumingEnumerable(CancellationToken cancellationToken)
{
while (true)
{
T item;
try
{
item = Take(cancellationToken);
}
catch (InvalidOperationException)
{
yield break;
}
yield return item;
}
}
/// <summary>
/// Provides a (synchronous) consuming enumerable for items in the producer/consumer queue.
/// </summary>
public IEnumerable<T> GetConsumingEnumerable()
{
return GetConsumingEnumerable(CancellationToken.None);
}
/// <summary>
/// Attempts to take an item.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param>
/// <param name="sync">Whether to run this method synchronously.</param>
/// <exception cref="InvalidOperationException">The collection has been marked complete for adding and is empty.</exception>
private async Task<T> DoTakeAsync(CancellationToken cancellationToken, bool sync)
{
using (sync ? _mutex.Lock() : await _mutex.LockAsync().ConfigureAwait(false))
{
while (Empty && !_completed)
{
if (sync)
_completedOrNotEmpty.Wait(cancellationToken);
else
await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false);
}
if (_completed && Empty)
throw new InvalidOperationException("Take failed; the producer/consumer collection has completed adding and is empty.");
if (!_collection.TryTake(out T item))
throw new InvalidOperationException("Take failed; the take from the underlying collection failed.");
_completedOrNotFull.Notify();
return item;
}
}
/// <summary>
/// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param>
public Task<T> TakeAsync(CancellationToken cancellationToken) => DoTakeAsync(cancellationToken, sync: false);
/// <summary>
/// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. This method may block the calling thread.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param>
public T Take(CancellationToken cancellationToken) => DoTakeAsync(cancellationToken, sync: true).WaitAndUnwrapException();
/// <summary>
/// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed.
/// </summary>
public Task<T> TakeAsync() => TakeAsync(CancellationToken.None);
/// <summary>
/// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. This method may block the calling thread.
/// </summary>
public T Take() => Take(CancellationToken.None);
[DebuggerNonUserCode]
internal sealed class DebugView
{
private readonly AsyncCollection<T> _collection;
public DebugView(AsyncCollection<T> collection)
{
_collection = collection;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] Items => _collection._collection.ToArray();
}
}
}