Created
August 30, 2018 11:17
-
-
Save kenanhancer/878ff48f56737c0947b50738f9399267 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 TPLExtensions | |
{ | |
public static async Task<TResult[]> ForEachConcurrentAsync<TItem, TResult>(this IEnumerable<TItem> enumerable, Func<TItem, Task<TResult>> action, int? maxDegreeOfParallelism = null) | |
{ | |
if (maxDegreeOfParallelism.HasValue) | |
{ | |
using (var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value)) | |
{ | |
var tasksWithThrottler = new List<Task<TResult>>(); | |
foreach (var item in enumerable) | |
{ | |
// Increment the number of currently running tasks and wait if they are more than limit. | |
await semaphoreSlim.WaitAsync(); | |
tasksWithThrottler.Add(Task.Run(async () => | |
{ | |
var result = await action(item); | |
// action is completed, so decrement the number of currently running tasks | |
semaphoreSlim.Release(); | |
return result; | |
})); | |
} | |
// Wait for all tasks to complete. | |
return await Task.WhenAll(tasksWithThrottler.ToArray()); | |
} | |
} | |
else | |
{ | |
return await Task.WhenAll(enumerable.Select(item => action(item))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment