1

I have a log after the loop Parallel.ForEach, and I want to be logged after the loop finished.

My code:

Parallel.ForEach(grpfiles, async Entry => { 
   await Process(Entry.ToList()); 
});
_logger.LogInformation($"End function  at:" + DateTime.Now);

Even I wrapped the loop like below, but not succeed it runs immediately:

await Task.Run(() => { 
   Parallel.ForEach(grpfiles, async Entry => { 
      await  Process(Entry.ToList());     
   }); 
});
_logger.LogInformation($"End function  at:" + DateTime.Now);
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • see https://stackoverflow.com/questions/7887072/how-can-i-wait-till-the-parallel-foreach-completes – Hossein Sabziani Oct 10 '22 at 13:49
  • 2
    In general, you *shouldn't* be combining `Parallel.ForEach` and async code. `Parallel.ForEach` supplies threads on which code can run. `async` either uses separate threads itself or defers to non-thread using mechanisms to arrange for the awaitable to become completed. – Damien_The_Unbeliever Oct 10 '22 at 13:54
  • 3
    If you want IO bound parallel handling, you could use the [Parallel.ForEachAsync](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.foreachasync?view=net-6.0) if you are using dotnet 6 or above. – Jeroen van Langen Oct 10 '22 at 14:08

0 Answers0