Skip to content

Instantly share code, notes, and snippets.

@ermish
Last active April 16, 2018 21:21
Show Gist options
  • Save ermish/5fdb9833bfca8932c0ae99122b0189ba to your computer and use it in GitHub Desktop.
Save ermish/5fdb9833bfca8932c0ae99122b0189ba to your computer and use it in GitHub Desktop.
C# ForEachAsync. Allows you to do sequential awaited tasks.(Set paralllelism to 1)
public static async Task<IEnumerable<U>> ForEachAsync<T, U>(this IEnumerable<T> items, Func<T, Task<U>> func, int _degreeOfParallelism = 100)
{
var results = new List<U>();
using (var semaphore = new SemaphoreSlim(_degreeOfParallelism))
{
var tasks = items.Select(async item =>
{
await semaphore.WaitAsync();
try
{
var result = await func(item);
results.Add(result);
}
finally
{
semaphore.Release();
}
}).ToArray();
await Task.WhenAll(tasks);
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment