Repository navigation
Expand file tree
/
Copy pathParallelEx.cs
More file actions
52 lines (44 loc) · 1.66 KB
/
Copy pathParallelEx.cs
File metadata and controls
52 lines (44 loc) · 1.66 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
// Copyright (c) 2011-2020 Roland Pheasant. All rights reserved.
// Roland Pheasant licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace DynamicData.Kernel;
internal static class ParallelEx
{
[SuppressMessage("Design", "CA2000: Dispose SemaphoreSlim", Justification = "Captured in lambda, can cause problems.")]
public static async Task<IEnumerable<TDestination>> SelectParallel<TSource, TDestination>(this IEnumerable<TSource> source, Func<TSource, Task<TDestination>> selector, int maximumThreads = 5)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (selector is null)
{
throw new ArgumentNullException(nameof(selector));
}
var semaphore = new SemaphoreSlim(maximumThreads);
var tasks = new List<Task<TDestination>>();
foreach (var item in source)
{
await semaphore.WaitAsync().ConfigureAwait(false);
tasks.Add(
Task.Run(
async () =>
{
try
{
return await selector(item).ConfigureAwait(false);
}
finally
{
semaphore.Release();
}
}));
}
return await Task.WhenAll(tasks).ConfigureAwait(false);
}
}