Last active
April 16, 2018 21:21
-
-
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)
This file contains 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 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