DEV Community

Discussion on: C#, Task.WhenAll vs Parallel.ForEach

alexandis profile image
alexandis • Edited on

Hi Garry, what about using async within Parallel.ForEach, like Parallel.ForEach(items, async (item) => {})? Does it make sense? My case is as follows: I am getting list of data from DB. Then, using Parallel.ForEach I'm checking the child entities - images. If each of image has FilePath - in our case it means the image is stored in file system and I need to read image data from stream into Image entity (byte[]). I'm using the above approach, but don't know if it has some dangerous pitfalls.

garryxiao profile image
Garry Xiao Author

Hi Alexandis, in the production environment, there are three points I would mention:

  1. Resource limitation. So after you read the list, if you want to use a different thread for each item, you need to know how many items there and inside the thread, how many images may have and the processing would have.
  2. If you make a new thread other than the main thread, async makes no sense. Maybe I am wrong.
  3. In multiple threads, fewer relations more benefits, pay attention to the lock issue.