Created
June 7, 2017 07:41
-
-
Save poulfoged/ef1d0d17a38c87029c48362718b1dcf5 to your computer and use it in GitHub Desktop.
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
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