JohanP
JohanP

Reputation: 5472

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?

Upvotes: 3

Views: 10493

Answers (2)

Jan Suchotzki
Jan Suchotzki

Reputation: 1426

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.

Upvotes: 5

John Wu
John Wu

Reputation: 52260

Some quick examples:

  1. A logging system where each worker thread can write to a queue and a worker thread is responsible for dequeuing items and writing them to a log file.

  2. To access an apartment-model COM server with expensive initialization, where it may be better to keep a single instance on its own thread.

  3. For logic that runs on a timer, e.g. a transaction that runs every 10 minutes to update an application variable with some sort of status.

  4. CPU-bound operations where individual response time is more important than server throughput.

  5. Logic that must continue to run after the HTTP response has been completed, e.g. if the total processing time would otherwise exceed an HTTP response timeout.

  6. Worker threads for system operations, e.g. a long running thread that checks for expired cache entries.

Upvotes: 4

Related Questions