Skip to content

Instantly share code, notes, and snippets.

@wahidustoz
Last active May 12, 2024 08:41
Show Gist options
  • Select an option

  • Save wahidustoz/6c9cde808563d9c0aa5905ece915fb6e to your computer and use it in GitHub Desktop.

Select an option

Save wahidustoz/6c9cde808563d9c0aa5905ece915fb6e to your computer and use it in GitHub Desktop.
/// <summary>
/// If the service uses dbContext, make sure to get another dbContext within ForEachAsync using service provider
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="maxDegreeOfParallelism"></param>
/// <param name="body"></param>
/// <returns></returns>
public static Task ForEachAsync<T>(IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism)
select Task.Run(async delegate
{
using (partition)
while (partition.MoveNext())
await body(partition.Current);
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment