-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAsyncEnumerableWorkerPool.cs
More file actions
229 lines (202 loc) · 7.58 KB
/
Copy pathAsyncEnumerableWorkerPool.cs
File metadata and controls
229 lines (202 loc) · 7.58 KB
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
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading.Channels;
namespace EnumerableAsyncProcessor;
/// <summary>
/// Processes asynchronous sources with a bounded channel and a fixed set of workers.
/// Source read-ahead and queued results stay proportional to worker count.
/// </summary>
internal static class AsyncEnumerableWorkerPool
{
internal static async Task ProcessAsync<TInput>(
IAsyncEnumerable<TInput> items,
Func<TInput, Task> taskSelector,
int workerCount,
CancellationToken cancellationToken)
{
using var pipelineCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var pipelineToken = pipelineCancellation.Token;
var channel = CreateChannel<TInput>(workerCount);
var exceptions = new ConcurrentQueue<Exception>();
var wasCanceled = 0;
var workers = StartWorkers(channel.Reader, taskSelector, workerCount, exceptions, () => Interlocked.Exchange(ref wasCanceled, 1), pipelineToken);
try
{
try
{
await foreach (var item in items.WithCancellation(pipelineToken).ConfigureAwait(false))
{
await channel.Writer.WriteAsync(item, pipelineToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
Interlocked.Exchange(ref wasCanceled, 1);
}
catch (Exception exception)
{
exceptions.Enqueue(exception);
}
finally
{
channel.Writer.TryComplete();
}
await Task.WhenAll(workers).ConfigureAwait(false);
ThrowIfFailed(exceptions, wasCanceled, cancellationToken);
}
finally
{
pipelineCancellation.Cancel();
channel.Writer.TryComplete();
}
}
internal static async IAsyncEnumerable<TOutput> ProcessResultsAsync<TInput, TOutput>(
IAsyncEnumerable<TInput> items,
Func<TInput, Task<TOutput>> taskSelector,
int workerCount,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
using var pipelineCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var pipelineToken = pipelineCancellation.Token;
var channel = CreateChannel<ResultWorkItem<TInput, TOutput>>(workerCount);
var workers = StartResultWorkers(channel.Reader, taskSelector, workerCount, pipelineToken);
var pendingResults = new Queue<Task<TOutput>>(workerCount);
try
{
await foreach (var item in items.WithCancellation(pipelineToken).ConfigureAwait(false))
{
var completionSource = new TaskCompletionSource<TOutput>(TaskCreationOptions.RunContinuationsAsynchronously);
await channel.Writer.WriteAsync(new ResultWorkItem<TInput, TOutput>(item, completionSource), pipelineToken).ConfigureAwait(false);
pendingResults.Enqueue(completionSource.Task);
if (pendingResults.Count == workerCount)
{
yield return await pendingResults.Dequeue().ConfigureAwait(false);
}
}
channel.Writer.TryComplete();
while (pendingResults.TryDequeue(out var resultTask))
{
yield return await resultTask.ConfigureAwait(false);
}
await Task.WhenAll(workers).ConfigureAwait(false);
}
finally
{
pipelineCancellation.Cancel();
channel.Writer.TryComplete();
try
{
await Task.WhenAll(workers).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pipelineToken.IsCancellationRequested)
{
// Expected when enumeration is canceled or the consumer stops early.
}
}
}
private static Channel<T> CreateChannel<T>(int capacity)
{
return Channel.CreateBounded<T>(new BoundedChannelOptions(capacity)
{
SingleWriter = true,
SingleReader = false,
FullMode = BoundedChannelFullMode.Wait,
AllowSynchronousContinuations = false
});
}
private static Task[] StartWorkers<TInput>(
ChannelReader<TInput> reader,
Func<TInput, Task> taskSelector,
int workerCount,
ConcurrentQueue<Exception> exceptions,
Action recordCancellation,
CancellationToken cancellationToken)
{
var workers = new Task[workerCount];
for (var i = 0; i < workerCount; i++)
{
workers[i] = Task.Run(async () =>
{
await foreach (var item in reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
Task? task = null;
try
{
task = taskSelector(item);
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
recordCancellation();
}
catch (Exception exception)
{
EnqueueExceptions(exceptions, task, exception);
}
}
}, cancellationToken);
}
return workers;
}
private static Task[] StartResultWorkers<TInput, TOutput>(
ChannelReader<ResultWorkItem<TInput, TOutput>> reader,
Func<TInput, Task<TOutput>> taskSelector,
int workerCount,
CancellationToken cancellationToken)
{
var workers = new Task[workerCount];
for (var i = 0; i < workerCount; i++)
{
workers[i] = Task.Run(async () =>
{
await foreach (var workItem in reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
Task<TOutput>? task = null;
try
{
task = taskSelector(workItem.Input);
workItem.CompletionSource.TrySetResult(await task.ConfigureAwait(false));
}
catch (Exception exception)
{
workItem.CompletionSource.TrySetFromFault(task, exception, cancellationToken);
}
}
}, cancellationToken);
}
return workers;
}
private static void EnqueueExceptions(
ConcurrentQueue<Exception> exceptions,
Task? task,
Exception exception)
{
if (task is { IsFaulted: true })
{
foreach (var innerException in task.Exception!.InnerExceptions)
{
exceptions.Enqueue(innerException);
}
return;
}
exceptions.Enqueue(exception);
}
private static void ThrowIfFailed(
ConcurrentQueue<Exception> exceptions,
int wasCanceled,
CancellationToken cancellationToken)
{
if (exceptions.TryDequeue(out var firstException))
{
ExceptionDispatchInfo.Capture(firstException).Throw();
}
if (wasCanceled != 0)
{
throw new OperationCanceledException(cancellationToken);
}
}
private readonly record struct ResultWorkItem<TInput, TOutput>(
TInput Input,
TaskCompletionSource<TOutput> CompletionSource);
}