Closed
Description
Background and motivation
#1946 recently Parallel.ForEachAsync
has been approved and added to .NET6. However there still no async of Parallel.For
. Developers still have to use the same workarounds as for Parallel.ForEach
on .NET5 and below to make it run asychronously. An async version of Parallel.For
has been mentioned two times in the linked issue, but was left out of discussion so I couldn't find a reason why it hasn't been made async yet. I simply assume that it wasn't taken into consideration because it was not explicit proposed.
As for the motivation I think the same arguments for Parallel.ForEachAsync
also applies to Parallel.ForAsync
API Proposal
namespace System.Threading.Tasks
{
public static class Parallel
{
public static Task ForAsync(int fromInclusive, int toExclusive, Func<int, CancellationToken, ValueTask> body);
public static Task ForAsync(int fromInclusive, int toExclusive, CancellationToken cancellationToken, Func<int, CancellationToken, ValueTask> body);
public static Task ForAsync(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Func<int, CancellationToken, ValueTask> body);
public static Task ForAsync(long fromInclusive, long toExclusive, Func<long, CancellationToken, ValueTask> body);
public static Task ForAsync(long fromInclusive, long toExclusive, CancellationToken cancellationToken, Func<long, CancellationToken, ValueTask> body);
public static Task ForAsync(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Func<long, CancellationToken, ValueTask> body);
}
}
API Usage
List<DuplicateItem> duplicates = new();
//duplicates.Add(...);
//...
await Parallel.ForAsync(0, duplicates.Count, new ParallelOptions { CancellationToken = cancellationTokenSource.Token}, async (i, token) => {
await duplicates.GenerateThumbnail();
for (int j = i + 1; j < duplicates.Count; j++) {
//...
}
});
Risks
No response