M
M
Matisumi2021-04-14 17:39:11
ASP.NET
Matisumi, 2021-04-14 17:39:11

Asp.net core webapi - sync/async controller methods?

I don't quite understand if there is a difference between asynchronous controller methods and synchronous methods in asp.net core webapi (3.1)?
As I understand it, each controller call is processed in a separate thread, which is taken from the thread pool. If the controller has a call to asynchronous methods - of course, the controller method must also be asynchronous. And if there is no call to asynchronous methods in the controller code, will there be any difference? Or maybe it makes sense to wrap this code without asynchronous calls in a task and evate it, making the controller method asynchronous?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-04-14
@Matisumi

And if there is no call to asynchronous methods in the controller code, will there be any difference?

If there are no asynchronous calls, then there is no point in making the controller method asynchronous.
Or maybe it makes sense to wrap this code without asynchronous calls in a task and evate it, making the controller method asynchronous?

No. Before and after the controller there are a bunch of middleware and Action / Result filters that are already asynchronous, so you will get all the benefits of asynchronous IO when working with HTTP
Read ASP.NET Core Performance Best Practices
Most importantly:

Don't:
  • Block asynchronous execution by calling Task.Wait or Task.Result.
  • Acquire locks in common code paths. ASP.NET Core apps are the most performant when architected to run code in parallel.
  • 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.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question