Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use Task.Run in Asp.Net Core?

I'm of the belief that you should never have to use Task.Run for any operation in .net core web context. If you have a long running task or CPU intensive task, you can offload it to a message queue for async processing. If you have a sync operation, that has no equivalent async method, then offloading to background thread does nothing for you, it actually makes in slightly worse.

What am I missing? Is there a genuine reason to use Task.Run in a high throughput server application?

like image 262
JohanP Avatar asked Oct 18 '25 20:10

JohanP


1 Answers

Just to backup your belief:

Do not: Call Task.Run and immediately await it. ASP.NET Core already runs app code on normal Thread Pool threads, so calling Task.Run only results in extra unnecessary Thread Pool scheduling. Even if the scheduled code would block a thread, Task.Run does not prevent that.

This is the official recommendation/best practice from Microsoft. Although it doesn't point out something you might have missed, it does tell you that it is a bad idea and why.

like image 61
Jan Suchotzki Avatar answered Oct 21 '25 10:10

Jan Suchotzki