Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always using Async in an ASP.NET MVC Controller

I recently inherited an ASP.NET MVC project. In that project, the developer is using async everywhere. I'm trying to assess if its a good idea or not. Specifically, I'm reviewing the controller code at the moment.

In the controllers, the developer wrote the stuff like the following:

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

Is there any advantage to this instead of the traditional version:

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

I could understand using async if await was used in the controller code. A lot of times, its not being used though. Is there any justification for this approach?

like image 311
user687554 Avatar asked Dec 13 '14 15:12

user687554


1 Answers

No. That's not a good idea to use Async everywhere.

Regarding the missing await the compiler issues a warning when an Async method does not contain an Await operator. An Async method without an await will run synchronously, which makes the semantics incorrect.

For your specific example, the operation is simple and short running, and that's why using Async/Await does not bring any benefits, and it shouldn't be used, so you are perfectly fine using:

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

Async/Await should be used for controller methods that perform some kind of IO (e.g. Network requests, Database access etc.). If a controller method is doing CPU bound work (e.g. math. calculations), then using Async/Await can actually make performance worse, unless your measurements prove me wrong.

The old rule applies: Measure twice, cut once.

like image 177
Faris Zacina Avatar answered Nov 13 '22 13:11

Faris Zacina