Skip to content

Instantly share code, notes, and snippets.

@scattered-code
Last active January 6, 2020 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scattered-code/1a4a01c3f3a24ebce293a6e7b4451254 to your computer and use it in GitHub Desktop.
Save scattered-code/1a4a01c3f3a24ebce293a6e7b4451254 to your computer and use it in GitHub Desktop.
public static Task ParallelForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
async Task AwaitPartition(IEnumerator<T> partition)
{
using (partition)
{
while (partition.MoveNext())
{ await body(partition.Current); }
}
}
return Task.WhenAll(
Partitioner
.Create(source)
.GetPartitions(dop)
.AsParallel()
.Select(p => AwaitPartition(p)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment