BotGenerator/Common/Extensions/ParallelExtensions.cs
chomp c9c472882e merge into main (#1)
Co-authored-by: Chomp <chomp@noreply.dev.sp-tarkov.com>
Co-authored-by: Dev <dev@noreply.dev.sp-tarkov.com>
Co-authored-by: Dev <dev@dev.sp-tarkov.com>
Reviewed-on: chomp/BotGenerator#1
2023-08-15 09:29:16 +00:00

32 lines
955 B
C#

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Common.Extensions
{
public static class ParallelExtensions
{
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 Task.Yield(); // prevents a sync/hot thread hangup
await body(partition.Current);
}
}
}
return Task.WhenAll(
Partitioner
.Create(source)
.GetPartitions(dop)
.AsParallel()
.Select(p => AwaitPartition(p)));
}
}
}