0

I read Is Task.Run considered bad practice in an ASP .NET MVC Web Application? which recommends against using Task.Run().

However, what if you had 3 different intensive CPU bound methods you wanted to run in parallel.

Couldn't you use await Task.WhenAll(task1, task2, task3)?

Wouldn't this result in a response being sent to the client sooner, at the expense of having fewer threads in the thread pool available to pick up new HTTP requests?

David Klempfner
  • 8,700
  • 20
  • 73
  • 153

1 Answers1

2

Wouldn't this result in a response being sent to the client sooner, at the expense of having fewer threads in the thread pool available to pick up new HTTP requests?

Yes. But you're probably underestimating the impact it would have on your scalability. If you want to do this, be sure to do load testing with and without parallelism before putting this into production.

I can say from experience that every single time I've done this, I've had to roll it back later.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • For argument's sake, let's say the performance hit you mentioned isn't that bad, would it then be true to say that the idea of "don't use `Task.Run()` in ASP.NET" only applies if you want to do one call to `Task.Run()`, because you're just using another thread for what could be done in the original thread? – David Klempfner Sep 29 '22 at 10:28
  • I've implemented something similar to what I mentioned in my question, for an Azure health check endpoint. The reason being that the response must take < 60s otherwise Azure considers the instance to be unhealthy. Some things I'm running in Tasks are connections to CosmosDb, Azure Service Bus etc. Would this scenario justify using many `Task.Run()`s? – David Klempfner Sep 29 '22 at 10:34
  • @DavidKlempfner: Those sound like I/O tasks rather than CPU tasks; in that case I would use `Task.WhenAll`. – Stephen Cleary Sep 29 '22 at 12:51