Created
August 20, 2017 16:27
-
-
Save sergey-tihon/5d29449ccacde78a407ae53906207a41 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class TplHelpers | |
{ | |
public static async Task<List<T2>> ExecuteInParallel<T1,T2>(this IEnumerable<T1> collection, | |
Func<T1, Task<T2>> processor, | |
int degreeOfParallelism) | |
{ | |
var queue = new ConcurrentQueue<T1>(collection); | |
var result = new ConcurrentBag<T2>(); | |
var tasks = Enumerable.Range(0, degreeOfParallelism).Select(async _ => | |
{ | |
while (queue.TryDequeue(out T1 item)) | |
{ | |
var r = await processor(item); | |
result.Add(r); | |
} | |
}); | |
await Task.WhenAll(tasks); | |
return result.ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment