Always use Async in ASP.NET MVC Controller

I recently inherited an ASP.NET MVC project. In this project, the developer uses async

everywhere. I am trying to assess if this is a good idea or not. Specifically, I am looking at the controller code at the moment.

In controllers, the developer wrote the following:

public async Task<ActionResult> Index()
{
  return View();
}

      

Is there any advantage over the traditional version:

public ActionResult Index()
{
  return View();
}

      

I could figure out using async

if in the controller code was used await

. Many times, it hasn't been used. Is there a justification for this approach?

+3


source to share


2 answers


Not. It's not a good idea to use Async everywhere.

For missing expectations, the compiler issues a warning when the method Async

does not contain a statement Await

. An Async method without waiting will execute synchronously, which makes the semantics incorrect.

In your specific example, the operation is simple and short, and so there is no benefit to using Async / Await, and should not be used, so you can use just fine:



public ActionResult Index()
{
    return View();
}

      

Async / Await should be used for controller methods that do some type of I / O (like network requests, database access, etc.). If the controller method does CPU bound work (like math) then using Async / Await can really hurt performance if your measurements don't give me an error.

The old rule applies: Measure twice, cut once .

+5


source


It makes no sense to do an action / method if there is no one in this method await

. The way to create async

means a state machine will be created "under the field" (by the compiler), which makes a little overhead compared to the pure void version (actually a small overhead, but if you have millions of requests per second that might change situation;)), If you are afraid that an expectation may appear soon (you have every reason to be "afraid"), and you have a lot of code that depends on this method (for example, this is an abstract method of a class / it belongs to an interface), you should keep the method returning Task<ActionResult>

, but don't mark it asynchronous. Example:

public Task<ActionResult> MyAction() {

    return Task.FromResult<ActionResult>(View());
}

      



This method Task.FromResult<T>

returns a completed task that prevents the compiler from creating an asynchronous state machine.

Back to the main question - it looks like the people who wrote this code didn't know what they were doing - the async marking method does not mean that the method works "asynchronously".

0


source







All Articles