Repository navigation
Expand file tree
/
Copy pathParallelEx.cs
More file actions
63 lines (55 loc) · 1.95 KB
/
Copy pathParallelEx.cs
File metadata and controls
63 lines (55 loc) · 1.95 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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace DynamicData.Kernel
{
internal static class ParallelEx
{
public static async Task<IEnumerable<TDestination>> SelectParallel<TSource, TDestination>(this IEnumerable<TSource> source, Func<TSource, Task<TDestination>> selector, int maximumThreads = 5)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (selector == 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();
tasks.Add(Task.Run(async () =>
{
try
{
return await selector(item);
}
finally
{
semaphore.Release();
}
}));
}
return await Task.WhenAll(tasks);
}
public static async Task<IEnumerable<T>> SelectParallel<T>(this IEnumerable<Task<T>> source, int maximumThreads = 5)
{
if (source == null) throw new ArgumentNullException(nameof(source));
var semaphore = new SemaphoreSlim(maximumThreads);
var tasks = new List<Task<T>>();
foreach (var task in source)
{
await semaphore.WaitAsync();
tasks.Add(Task.Run(async () =>
{
try
{
return await task;
}
finally
{
semaphore.Release();
}
}));
}
return await Task.WhenAll(tasks);
}
}
}