Home > Mobile >  How run Async method in ForEach, for each record, and dont wait fo each result
How run Async method in ForEach, for each record, and dont wait fo each result

Time:10-18

I would like each record in ForEach run Async. I don't have to wait for each result, so I can just iterate through the list and commission the record executed in the next Thread. But in the end, I need to return this list with all executed methods. Does anyone know how I could refactor this example code?

Example:

List<SomeObject> CalculateMissingVar(List<SomeObject> records)
{
    foreach (var record in records)
    {
        //I woudl like run this method async without wating for each result
        record.PlaceForLongMathEquation = Calculate(5);
    }

    return records;
}

//This method shodul be Async
int Calculate(int number)
{
    return number * number;
}

CodePudding user response:

If each iteration of your loop does not depend on the previous iteration then you can use Parallel.ForEach, it sounds like this is exactly what you are looking for (it performs all iterations of the loops asynchronously in parallel with each other according to the number of cores on your server)

You can read about it here https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop

List<SomeObject> CalculateMissingVar(List<SomeObject> records)
{
    Parallel.ForEach(records, record =>
    {
        //I woudl like run this method async without wating for each result
        record.PlaceForLongMathEquation = Calculate(5);
    }

    return records;
}

CodePudding user response:

Proper error handling omitted for compactness:

async Task CalculateMissingVar(List<SomeObject> records)
{
    await Task.WhenAll(records.Select(Calculate));
}

async Task Calculate(SomeObject record)
{
    ...
    record.PlaceForLongMathEquation = x;
}
  • Related