Skip to content

Instantly share code, notes, and snippets.

@kenanhancer
Created August 30, 2018 11:17
Show Gist options
  • Save kenanhancer/878ff48f56737c0947b50738f9399267 to your computer and use it in GitHub Desktop.
Save kenanhancer/878ff48f56737c0947b50738f9399267 to your computer and use it in GitHub Desktop.
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