Last active
April 2, 2021 03:36
-
-
Save goncalo-oliveira/d5cb402ee179f5ef435f352d21852d23 to your computer and use it in GitHub Desktop.
Async Parallel.ForEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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