AspNetCoreDiagnosticScenarios icon indicating copy to clipboard operation
AspNetCoreDiagnosticScenarios copied to clipboard

How can Task.Run be considered good on ASP.NET?

Open paulomorgado opened this issue 5 years ago • 5 comments

IT might be less bad, but good???

paulomorgado avatar Nov 13 '18 09:11 paulomorgado

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.

davidfowl avatar Nov 17 '18 22:11 davidfowl

For fire and forget, I'd choose any option on this page over Task.Run.

paulomorgado avatar Nov 18 '18 22:11 paulomorgado

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.

davidfowl avatar Nov 18 '18 23:11 davidfowl

The hosting environment can make some guarantees about work it's managing. It can make nothing about Task.Run. Or can it?

paulomorgado avatar Nov 18 '18 23:11 paulomorgado

Yes, you can write it such that the background task is aware of the host lifetime, that's about it.

davidfowl avatar Nov 19 '18 07:11 davidfowl