4

I've read that using Task.Run in an ASP.NET web app was a bad idea as it uses another thread from the thread pool and hence prevent this particular thread from being used to serve a request.

Isn't the same situation with Parallel.ForEach? Won't it use multiple threads from the thread pool and hence prevent these particular threads from being used to serve a request ?

Anthony Hocquet
  • 348
  • 1
  • 3
  • 9
  • `Task.Run` is bad, `Parallel.ForEach` isn't. Task.Run will use another thread without providing any benefit. Parallel.ForEach will complete faster at the (possible) expense of other requests. This may or may not be a problem – Panagiotis Kanavos Mar 17 '17 at 14:42

1 Answers1

10

Isn't the same problem with Parallel.ForEach? Won't it use multiple threads from the thread pool and hence prevent these particular threads from being used to serve a request?

Yes, it will. This means that you'd be decreasing the total throughput of your server by having requests using up multiple requests like this. That individual request would complete faster, but it would complete faster at the expense of other requests.

This also assumes that your machine is under a high load. If there isn't a sufficiently high load on the thread pool, then it could afford to dedicate more resources for that request without inhibiting the ability of other requests to be served, and dedicating more resources for that request may well speed up that request.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Thanks Servy, you confirmed what I thought. – Anthony Hocquet Mar 15 '17 at 21:34
  • One could say that `Task.Run` is worse, because it will use another thread without any speed benefit. Parallel.ForEach will finish faster though. The impact on other requests may or may not be a problem – Panagiotis Kanavos Mar 17 '17 at 14:43
  • 1
    @PanagiotisKanavos Well you can use `Task.Run` in such a way that you have parallelism going on. But yes, if you *don't* have parallelism going on, and are just using multiple threads to do sequential work, then you both use more resources and don't even speed up that request. – Servy Mar 17 '17 at 14:45
  • On top of that, the DOP should not be left at the default value, otherwise `Parallel.ForEach` may spawn as many tasks as cores, throttling other requests. – Panagiotis Kanavos Mar 17 '17 at 14:51
  • @PanagiotisKanavos As mentioned in the answer, if you want to use `Parallel.ForEach` the *reason* to use it is because you want that request to be done faster at the risk of slowing down other requests (if your server is currently CPU bound), so if you're going to then go and restrict the degrees of parallelism you're preventing that from happening, so you might as well just have not used it in the first place. If you're using it at all, it's because you *want* that request to be sped up at the possible expense of others. – Servy Mar 17 '17 at 14:55