AspNetCoreDiagnosticScenarios
AspNetCoreDiagnosticScenarios copied to clipboard
How can Task.Run be considered good on ASP.NET?
IT might be less bad, but good???
Generally, there's no performance benefit to using Task.Run
in an ASP.NET Core application. You're already on a thread pool thread so you're just moving work off the existing thread pool thread onto another one. Now if you want to compute some data outside the scope of a request, then you may wish to return to the client before that data is computed then you can offload onto another task. That's one scenario where it's useful (fire and forget).
This comment really hits the nail on the head:
https://www.reddit.com/r/csharp/comments/9p26ci/diagnosing_net_core_threadpool_starvation_with/e7yteqs/
100% of the threads your code starts must finish faster than requests are coming in.
For fire and forget, I'd choose any option on this page over Task.Run
.
How does that improve the situation? This is all about understanding tradeoffs. The higher is that each requests is conceptually already running inside of a Task.Run (not quite but roughly speaking) so any other work that takes longer than anyone one request could be a bottleneck given the right set of load.
The hosting environment can make some guarantees about work it's managing. It can make nothing about Task.Run
. Or can it?
Yes, you can write it such that the background task is aware of the host lifetime, that's about it.