Skip to content

Instantly share code, notes, and snippets.

@goncalo-oliveira
Last active April 2, 2021 03:36
Show Gist options
  • Save goncalo-oliveira/d5cb402ee179f5ef435f352d21852d23 to your computer and use it in GitHub Desktop.
Save goncalo-oliveira/d5cb402ee179f5ef435f352d21852d23 to your computer and use it in GitHub Desktop.
Async Parallel.ForEach
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyNamespace
{
public static class ParallelAsync
{
public static Task ForEachAsync<T>( this IEnumerable<T> source, Func<T, Task> body )
{
Task completedTask = Task.WhenAll(
source.Select( item => body( item ) )
);
return ( completedTask );
}
public static Task ForEachAsync<T>( this IEnumerable<T> source, ParallelOptions parallelOptions, Func<T, Task> body )
{
Task completedTask = Task.WhenAll(
Partitioner.Create( source )
.GetPartitions( parallelOptions.MaxDegreeOfParallelism )
.Select( partition => Task.Run( async delegate
{
using ( partition )
{
while ( partition.MoveNext() )
{
await body( partition.Current );
}
}
}, parallelOptions.CancellationToken ) )
);
return ( completedTask );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment