Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading