Skip to content

Instantly share code, notes, and snippets.

@poulfoged
Created June 7, 2017 07:41
Show Gist options
  • Save poulfoged/ef1d0d17a38c87029c48362718b1dcf5 to your computer and use it in GitHub Desktop.
Save poulfoged/ef1d0d17a38c87029c48362718b1dcf5 to your computer and use it in GitHub Desktop.
internal static class AsyncHelper
{
public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
Partitioner.Create(source)
.GetPartitions(dop)
.Select(partition => Task.Run(async delegate
{
using (partition)
while (partition.MoveNext())
await body(partition.Current).ContinueWith(t =>
{
//observe exceptions
});
})));
}
public static async Task<IEnumerable<T2>> SelectParallel<T, T2>(this IEnumerable<T> source, int dop, Func<T, Task<T2>> action)
{
var concurrentTasks = Partitioner.Create(source)
.GetPartitions(dop)
.Select(partition => Task.Run(async delegate
{
using (partition)
{
var concurrentBag = new List<T2>();
while (partition.MoveNext())
concurrentBag.Add(await action(partition.Current));
return concurrentBag;
}
}));
var lists = await Task.WhenAll(concurrentTasks);
return lists.SelectMany(bag => bag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment