-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathParallelizer.cs
More file actions
343 lines (301 loc) · 16.6 KB
/
Copy pathParallelizer.cs
File metadata and controls
343 lines (301 loc) · 16.6 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
namespace SafeParallel
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
public static class Parallelizer
{
public static int MaxParallelismDefault { get; set; } = 100;
/// <summary>
/// Runs the action over all the input items.
/// There is no error handling - if the action throws an exception, it will blow and stop processing eventually.
/// If desired you can put error handling in the action.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <returns>A <see cref="Task"/> you should await - when it's done, all the items have been processed.</returns>
public static async Task SafeParallelAsync<TIn>(this IEnumerable<TIn> inputValues, Func<TIn, Task> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (inputValues is null)
{
throw new ArgumentNullException(nameof(inputValues));
}
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
var taskQueue = new Queue<Task>();
using var sem = new SemaphoreSlim(maxParallelism ?? MaxParallelismDefault);
foreach (var input in inputValues)
{
try
{
await sem.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
if (cancellationToken.IsCancellationRequested)
{
break;
}
var task = action(input);
taskQueue.Enqueue(RunIt(task, sem));
while (taskQueue.TryPeek(out var t) && t.IsCompleted)
{
await taskQueue.Dequeue();
}
}
await Task.WhenAll(taskQueue);
}
/// <summary>
/// Runs the action over all the input items.
/// There is no error handling - if the action throws an exception, it will blow and stop processing eventually.
/// If desired you can put error handling in the action.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The async enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <returns>A <see cref="Task"/> you should await - when it's done, all the items have been processed.</returns>
public static async Task SafeParallelAsync<TIn>(this IAsyncEnumerable<TIn> inputValues, Func<TIn, Task> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (inputValues is null)
{
throw new ArgumentNullException(nameof(inputValues));
}
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
var taskQueue = new Queue<Task>();
using var sem = new SemaphoreSlim(maxParallelism ?? MaxParallelismDefault);
await foreach (var input in inputValues.WithCancellation(cancellationToken))
{
try
{
await sem.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
if (cancellationToken.IsCancellationRequested)
{
break;
}
var task = action(input);
taskQueue.Enqueue(RunIt(task, sem));
while (taskQueue.TryPeek(out var t) && t.IsCompleted)
{
await taskQueue.Dequeue();
}
}
await Task.WhenAll(taskQueue);
}
/// <summary>
/// Runs the action over all the input items.
/// Exceptions are caught and stored on the result object.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <returns>An IAsyncEnumerable with a <see cref="Result{TIn}"/> that has the input value and any exception.</returns>
public static IAsyncEnumerable<Result<TIn>> SafeParallelAsyncWithResult<TIn>(this IEnumerable<TIn> inputValues, Func<TIn, Task> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return SafeParallelAsyncWithResult(inputValues, (TIn input, SemaphoreSlim sem) => RunIt(input, action, sem), maxParallelism ?? MaxParallelismDefault, cancellationToken);
}
/// <summary>
/// Runs the action over all the input items.
/// Exceptions are caught and stored on the result object.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <typeparam name="TOut">The type of result from the action.</typeparam>
/// <returns>An IAsyncEnumerable with a <see cref="Result{TIn, TOut}"/> that has the input value, the result and any exception.</returns>
public static IAsyncEnumerable<Result<TIn, TOut>> SafeParallelAsyncWithResult<TIn, TOut>(this IEnumerable<TIn> inputValues, Func<TIn, Task<TOut>> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return SafeParallelAsyncWithResult(inputValues, (TIn input, SemaphoreSlim sem) => RunIt(input, action, sem), maxParallelism ?? MaxParallelismDefault, cancellationToken);
}
/// <summary>
/// Runs the action over all the input values.
/// Exceptions are caught and stored on the result object.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The async enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <returns>An IAsyncEnumerable with a <see cref="Result{TIn}"/> that has the input value and any exception.</returns>
public static IAsyncEnumerable<Result<TIn>> SafeParallelAsyncWithResult<TIn>(this IAsyncEnumerable<TIn> inputValues, Func<TIn, Task> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return SafeParallelAsyncWithResult(inputValues, (TIn input, SemaphoreSlim sem) => RunIt(input, action, sem), maxParallelism ?? MaxParallelismDefault, cancellationToken);
}
/// <summary>
/// Runs the action over all the input values.
/// Exceptions are caught and stored on the result object.
/// This will only keep a relatively small number of tasks and input values in scope so can safely be used with
/// streaming IEnumerables that you are reading from an external source.
/// </summary>
/// <param name="inputValues">The async enumerable that has the values to be passed to the action.</param>
/// <param name="action">The action you want to perfom on each item in the enumerable.</param>
/// <param name="maxParallelism">The maximum number of tasks to run in parallel.</param>
/// <param name="cancellationToken">A cancellation token you can use to stop the processing. If cancelled, the already-enqueed tasks will still be awaited but no more tasks will be enqued. This will not throw a <see cref="TaskCancelledException" />.</param>
/// <typeparam name="TIn">The type of the values in inputValues.</typeparam>
/// <typeparam name="TOut">The type of the return value from the action.</typeparam>
/// <returns>An IAsyncEnumerable with a <see cref="Result{TIn, TOut}"/> that has the input value, the result and any exception.</returns>
public static IAsyncEnumerable<Result<TIn, TOut>> SafeParallelAsyncWithResult<TIn, TOut>(this IAsyncEnumerable<TIn> inputValues, Func<TIn, Task<TOut>> action, int? maxParallelism = null, CancellationToken cancellationToken = default)
{
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
return SafeParallelAsyncWithResult(inputValues, (TIn input, SemaphoreSlim sem) => RunIt(input, action, sem), maxParallelism ?? MaxParallelismDefault, cancellationToken);
}
private static async IAsyncEnumerable<TResult> SafeParallelAsyncWithResult<TIn, TResult>(IEnumerable<TIn> inputValues, Func<TIn, SemaphoreSlim, Task<TResult>> runner, int? maxParallelism = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (inputValues is null)
{
throw new ArgumentNullException(nameof(inputValues));
}
var taskQueue = new Queue<Task<TResult>>();
using var sem = new SemaphoreSlim(maxParallelism ?? MaxParallelismDefault);
foreach (var input in inputValues)
{
try
{
await sem.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
if (cancellationToken.IsCancellationRequested)
{
break;
}
taskQueue.Enqueue(runner(input, sem));
// Return the tasks that have already compleed
while (taskQueue.TryPeek(out var t) && t.IsCompleted)
{
// As far as I can fathom, there is no way this could throw an exception so not handling it
yield return await taskQueue.Dequeue();
}
}
foreach (var task in taskQueue)
{
yield return await task;
}
}
private static async IAsyncEnumerable<TResult> SafeParallelAsyncWithResult<TIn, TResult>(IAsyncEnumerable<TIn> inputValues, Func<TIn, SemaphoreSlim, Task<TResult>> runner, int? maxParallelism = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (inputValues is null)
{
throw new ArgumentNullException(nameof(inputValues));
}
var taskQueue = new Queue<Task<TResult>>();
using var sem = new SemaphoreSlim(maxParallelism ?? MaxParallelismDefault);
await foreach (var input in inputValues.WithCancellation(cancellationToken))
{
try
{
await sem.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
if (cancellationToken.IsCancellationRequested)
{
break;
}
taskQueue.Enqueue(runner(input, sem));
// Return the tasks that have already compleed
while (taskQueue.TryPeek(out var t) && t.IsCompleted)
{
// As far as I can fathom, there is no way this could throw an exception so not handling it
yield return await taskQueue.Dequeue();
}
}
foreach (var task in taskQueue)
{
yield return await task;
}
}
private static async Task<Result<TIn>> RunIt<TIn>(TIn input, Func<TIn, Task> action, SemaphoreSlim sem)
{
#pragma warning disable CA1031
try
{
await action(input);
return new Result<TIn>(input);
}
catch (Exception e)
{
return new Result<TIn>(input, e);
}
finally
{
sem.Release();
}
#pragma warning restore CA1031
}
private static async Task<Result<TIn, TOut>> RunIt<TIn, TOut>(TIn input, Func<TIn, Task<TOut>> action, SemaphoreSlim sem)
{
#pragma warning disable CA1031
try
{
TOut output = await action(input);
return new Result<TIn, TOut>(input, output);
}
catch (Exception e)
{
return new Result<TIn, TOut>(input, e);
}
finally
{
sem.Release();
}
#pragma warning restore CA1031
}
private static async Task RunIt(Task task, SemaphoreSlim sem)
{
await task;
sem.Release();
}
}
}