-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
HandleableCollection.cs
279 lines (240 loc) · 9.3 KB
/
HandleableCollection.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.NETCore.Client
{
/// <summary>
/// A collection of objects that allows for observability and mutability using handlers.
/// </summary>
internal class HandleableCollection<T> : IEnumerable<T>, IDisposable
{
public delegate bool Handler(T item, out bool removeItem);
/// <summary>
/// Accepts the first item it encounters and requests that the item is removed from the collection.
/// </summary>
private static readonly Handler DefaultHandler = (T item, out bool removeItem) => { removeItem = true; return true; };
private readonly List<T> _items = new List<T>();
private readonly List<Tuple<TaskCompletionSource<T>, Handler>> _handlers = new List<Tuple<TaskCompletionSource<T>, Handler>>();
private bool _disposed = false;
/// <summary>
/// Returns an enumerator that iterates through the underlying collection.
/// </summary>
/// <remarks>
/// The returned enumerator is over a copy of the underlying collection so that there are no concurrency issues.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
IList<T> copy;
lock (_items)
{
VerifyNotDisposed();
copy = _items.ToList();
}
return copy.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the underlying collection.
/// </summary>
/// <remarks>
/// The returned enumerator is over a copy of the underlying collection so that there are no concurrency issues.
/// </remarks>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
IList<T> copy;
lock (_items)
{
VerifyNotDisposed();
copy = _items.ToList();
}
return copy.GetEnumerator();
}
/// <summary>
/// Disposes the <see cref="HandleableCollection{T}"/> by clearing all items and handlers.
/// </summary>
/// <remarks>
/// All pending handlers with throw <see cref="ObjectDisposedException"/>.
/// </remarks>
public void Dispose()
{
lock (_items)
{
if (_disposed)
{
return;
}
_disposed = true;
}
RemoveAndDisposeItems();
foreach (Tuple<TaskCompletionSource<T>, Handler> tuple in _handlers)
{
tuple.Item1.TrySetException(new ObjectDisposedException(nameof(HandleableCollection<T>)));
}
_handlers.Clear();
}
/// <summary>
/// Adds an item so that it may be observed by a handler.
/// </summary>
/// <param name="item">Item to add to the collection.</param>
/// <remarks>
/// The item may be immediately consumed if a handler removes the item, thus it may
/// not be stored into the underlying list.
/// </remarks>
public void Add(in T item)
{
lock (_items)
{
VerifyNotDisposed();
bool handledValue = false;
for (int i = 0; !handledValue && i < _handlers.Count; i++)
{
Tuple<TaskCompletionSource<T>, Handler> handler = _handlers[i];
if (TryHandler(item, handler.Item2, handler.Item1, out handledValue))
{
_handlers.RemoveAt(i);
i--;
}
}
if (!handledValue)
{
_items.Add(item);
}
}
}
/// <summary>
/// Returns the first item offered to the handler
/// or waits for a future item if no item is immediately available.
/// </summary>
/// <param name="timeout">The amount of time to wait before cancelling the handler.</param>
/// <returns>The first item offered to the handler.</returns>
public T Handle(TimeSpan timeout) => Handle(DefaultHandler, timeout);
/// <summary>
/// Returns the item on which the handler completes or waits for future items
/// if the handler does not immediately complete.
/// </summary>
/// <param name="handler">The handler that determines on which item to complete.</param>
/// <param name="timeout">The amount of time to wait before cancelling the handler.</param>
/// <returns>The item on which the handler completes.</returns>
public T Handle(Handler handler, TimeSpan timeout)
{
using var cancellation = new CancellationTokenSource(timeout);
var completionSource = new TaskCompletionSource<T>();
using var _ = cancellation.Token.Register(
() => completionSource.TrySetException(new TimeoutException()));
RunOrQueueHandler(handler, completionSource);
try
{
return completionSource.Task.Result;
}
catch (AggregateException ex)
{
throw ex.GetBaseException();
}
}
/// <summary>
/// Returns the first item offered to the handler
/// or waits for a future item if no item is immediately available.
/// </summary>
/// <param name="token">The token to monitor for cancellation requests.</param>
/// <returns>A task that completes with the first item offered to the handler.</returns>
public Task<T> HandleAsync(CancellationToken token) => HandleAsync(DefaultHandler, token);
/// <summary>
/// Returns the item on which the handler completes and waits for future items
/// if the handler does not immediately complete.
/// </summary>
/// <param name="handler">The handler that determines on which item to complete.</param>
/// <param name="token">The token to monitor for cancellation requests.</param>
/// <returns>A task that completes with the item on which the handler completes.</returns>
public async Task<T> HandleAsync(Handler handler, CancellationToken token)
{
var completionSource = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
using var _ = token.Register(() => completionSource.TrySetCanceled(token));
RunOrQueueHandler(handler, completionSource);
return await completionSource.Task.ConfigureAwait(false);
}
private void RunOrQueueHandler(Handler handler, TaskCompletionSource<T> completionSource)
{
lock (_items)
{
VerifyNotDisposed();
OnHandlerBegin();
bool stopHandling = false;
for (int i = 0; !stopHandling && i < _items.Count; i++)
{
T item = _items[i];
stopHandling = TryHandler(item, handler, completionSource, out bool removeItem);
if (removeItem)
{
_items.RemoveAt(i);
i--;
}
}
if (!stopHandling)
{
_handlers.Add(Tuple.Create(completionSource, handler));
}
}
}
private static bool TryHandler(in T item, Handler handler, TaskCompletionSource<T> completionSource, out bool removeItem)
{
removeItem = false;
if (completionSource.Task.IsCompleted)
{
return true;
}
bool stopHandling = false;
try
{
stopHandling = handler(item, out removeItem);
}
catch (Exception ex)
{
completionSource.TrySetException(ex);
return true;
}
if (stopHandling)
{
completionSource.TrySetResult(item);
}
return stopHandling;
}
/// <summary>
/// Clears all items from the collection.
/// </summary>
public void ClearItems()
{
lock (_items)
{
VerifyNotDisposed();
RemoveAndDisposeItems();
}
}
private void RemoveAndDisposeItems()
{
foreach (T item in _items)
{
if (item is IDisposable disposable)
{
disposable.Dispose();
}
}
_items.Clear();
}
private void VerifyNotDisposed()
{
Debug.Assert(Monitor.IsEntered(_items));
if (_disposed)
{
throw new ObjectDisposedException(nameof(HandleableCollection<T>));
}
}
protected virtual void OnHandlerBegin()
{
}
}
}