Skip to content

Instantly share code, notes, and snippets.

@scattered-code
Last active June 29, 2021 05:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scattered-code/83c3a733bcbdef1f492846cb6996a298 to your computer and use it in GitHub Desktop.
Save scattered-code/83c3a733bcbdef1f492846cb6996a298 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Extensions
{
public static class Extensions
{
public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
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