Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
Doctor Ford Avatar asked Sep 09 '25 18:09

Doctor Ford


1 Answers

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?

like image 114
Guru Stron Avatar answered Sep 12 '25 08:09

Guru Stron