Search code examples
c#asynchronousparallel-processingparallel.foreachasync

Using Parallel.ForEachAsync


I'm trying to run a Parallel.ForEachAsync(), but I am getting these two errors:

Error 1:
Argument 2: can not convert from System.Threading.Tasks.ParallelOptions to System.Threading.CancellationToken
Error 2:
Delegate Func<WC, CancellationToken, ValueTask> does not take 1 argument

And this is my code:

public async Task<List<DisplayDto>> GetData()
{
    var options = new ParallelOptions()
    {
        MaxDegreeOfParallelism = 20;
    };

    await Parallel.ForEachAsync(result, options, async OrderNumber => {
        //Do Stuff here. 
    });
}

What must be altered in order for this to work as I want?


Solution

  • Parallel.ForEachAsync expects Func<TSource, CancellationToken, ValueTask> i.e. accepting 2 parameters (first one being an element of collection and second one - CancellationToken), not one. Usage can look like that:

    public async Task<List<DisplayDto>> GetData()
    {
        var options = new ParallelOptions()
        {
            MaxDegreeOfParallelism = 20
        };
    
        await Parallel.ForEachAsync(result, options, async (OrderNumber, ct) => {
            // do not forget to use CancellationToken (ct) where appropriate 
            // Do Stuff here. 
        });
     }
    

    Example.

    Also can be useful - The need for two cancellation tokens in .NET 6 Parallel.ForEachAsync?