Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.ForAsync in C# .NET?

I want to execute a for loop in C# in parallel asynchronously. But the Parallel class contains only a synchronous For method and an asynchronous ForEachAsync method (.NET 6). This looks like an oversight to me.

Where is the Parallel.ForAsync method? Is there any workaround?


2 Answers

I agree,
not having a Parallel.ForAsync method looks like an enormous oversight. I have good news for you though: in .NET 8 and C#12 (coming out soon at 23. november 2023) this will be resolved. Parallel.ForAsync

The Parallel.ForAsync API was introduced in .NET 8. It has the three following overloads:

public static Task ForAsync<T>(T fromInclusive, T toExclusive,
    Func<T, CancellationToken, ValueTask> body)
    where T : notnull, IBinaryInteger<T>;

public static Task ForAsync<T>(T fromInclusive, T toExclusive,
    CancellationToken cancellationToken, Func<T, CancellationToken, ValueTask> body)
    where T : notnull, IBinaryInteger<T>;

public static Task ForAsync<T>(T fromInclusive, T toExclusive,
    ParallelOptions parallelOptions, Func<T, CancellationToken, ValueTask> body)
    where T : notnull, IBinaryInteger<T>;

It is the first public .NET API to be based on the generic math interfaces introduced in .NET 7.

Usage example:

ParallelOptions options = new() { MaxDegreeOfParallelism = 2 };

await Parallel.ForAsync(0, 100, options, async (i, ct) =>
{
   // Process the i element (here the type of i is int)
});

More information and benchmarks about this API can be found in this Microsoft document. Also here is the API proposal.

like image 24
Theodor Zoulias Avatar answered Feb 22 '26 17:02

Theodor Zoulias