Here's an example of using ParalleForEach Async in C#
Reference: C#: ParallelForEachAsync by Alexandru Puiu
/// <summary>
/// Extension method for ParallelForEachAsync/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="dop"></param>
/// <param name="body"></param>
/// <returns></returns>
public static Task ParallelForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
async Task AwaitPartition(IEnumerator<T> partition)
{
using (partition)
{
while (partition.MoveNext())
{ await body(partition.Current); }
}
}
return Task.WhenAll(
Partitioner
.Create(source)
.GetPartitions(dop)
.AsParallel()
.Select(p => AwaitPartition(p)));
}
Usage:
#region Extension method for ParallelForEachAsync: usage
//await GetDocumentsFromDatabase(session).ForEachAsync(dop: 20, body: async entry =>
//{
// _logger.Info($"Processing entry '{entry.Id}'");
//});
#endregion
//await GetDocumentsFromDatabase(session).ForEachAsync(dop: 20, body: async entry =>
//{
// _logger.Info($"Processing entry '{entry.Id}'");
//});
#endregion
No comments:
Post a Comment