Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • 1
    I think this result is obvious, cause you start Async Method from ForEach Body (i.e. using new ThreadPool Thread without waiting for result). Here we must call DoSomethingAsync(i, prefix).Result. Commented Jul 9, 2021 at 11:11
  • @Mic While the result may seem obvious for you, the result of using Parallel.ForEach inappropriately in a web application can cause some serious issues within a server that will not appear until a load is put on the app. The post is not to say you shouldn't use it, but to make sure those who do use it know what is actually going to happen. Additionally, you should avoid using .Result as you should always be using async/await. Commented Jul 17, 2021 at 16:33
  • 2
    Parallel.ForEach cannot be used for async method calls. As DoSomething returns a Task which is not awaited, you should call .Wait() on it. Now you'll see that Parallel.ForEach returns only after all work is done. Commented Aug 27, 2021 at 8:37
  • @Bouke the point of the answer is to help those that are not aware of the differences. That said, you can use a task within Parallel.ForEach, but it will not be executed on the main thread. That does not mean you should, but it is allowable in the code as the example demonstrates. This means the code in the task is executing on a different thread and not blocked. There are scenarios where someone may want to have this occur, but they should be aware of what is happening. Commented Aug 27, 2021 at 17:34
  • 1
    Using the Parallel.ForEach with async delegate is a bug. The resulting behavior is never desirable. The correct API for parallelizing asynchronous work is the Parallel.ForEachAsync. The question makes no mention that the underlying work can be asynchronous, so this answer is off topic, hence my downvote. Commented Jan 19, 2023 at 5:24