0

I am working on C# Parallel.ForEach loop. Within the parallel loop, I am calling async method ProcessMyData and ProcessMyData calling another async method GetMarkedData where in GetMarkedData method, I am calling the API services to pull record from database via Azure Function API but with parallel loop, I never received data for first thread while this method GetMarkedData been called for remaining record and I never receive data in parallel loop however it do work fine in classic loop.

Parallel.ForEach(myList, options, async item=>
{
    var processDataList = await ProcessMyData(item.Id);
});

protected async Task<List<myRecord>> ProcessMyData(recordId)
{
    //my code...
 
    var data = await GetMarkedData(recordId);
    // remaining code...
}

public virtual async Task<IEnumerable<Record>> GetMarkedData(recordId id)
{
    using (var myService = HttpClientUtilities...)
    {
        var markedRecordlist = myService.GetData(...)   
    }
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • 4
    `Parallel.ForEach` is used for computational purposes not IO, no async here. Use a `List` in combination with `Task.WhenAll()` or use the Dotnet 6 [`Parallel.ForEachAsync()`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.foreachasync?view=net-6.0) – Jeroen van Langen Feb 22 '22 at 08:28
  • 2
    There's a duplicate somewhere on SO but I can't find it. The issue is that `Parallel.ForEach` has no overload which takes a `Func`, so your async lambda gets turned into an `async void`, which means that `Parallel.ForEach` has no idea when it's finished -- so it can't wait for your lambda to complete – canton7 Feb 22 '22 at 08:40
  • @canton Is this the one you want?: https://stackoverflow.com/questions/15136542/parallel-foreach-with-asynchronous-lambda – ProgrammingLlama Feb 22 '22 at 08:40
  • 1
    @Llama That one starts with the asker identifying what the problem is. IIRC there's another one where the answers do a good job of explaining the problem itself, but maybe I'm just making it up. That one will do, anyway -- it has the answer suggesting `ForEachAsync` – canton7 Feb 22 '22 at 08:42

0 Answers0