I was looking at ASP.NET MVC 5 templates and I have notice that many of the actions and marked as async:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { }
When should I do this on an MVC action? When it contains access to a database?
If I call a repository inside the action should I also use Task to make it async?
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
Media Server responds to an asynchronous action immediately. This means that you do not have to wait for a response if the action takes a long time. The response to an asynchronous action includes only a token. You can use this token to determine the status of the task through the QueueInfo action at a later time.
Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.
The asynchronous controller enables you to write asynchronous action methods. It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action.
The core of your questions is: When should I make my MVC actions async? See http://blogs.msdn.com/b/rickandy/archive/2009/11/14/should-my-database-calls-be-asynchronous.aspx for a good discussion of the issue. He talks about the database only, but his points carry over.
Essentially, almost never call the database in an async way.
For database applications using async operations to reduce the number of blocked threads on the web server is almost always a complete waste of time.
Don't be detracted by people telling you to always use async IO if possible. Async is all the rage right now. Lot's of irrational advice is being spread.
Entity Framework 6 (used by default with MVC 5) now supports async database calls, so the action method signatures have been update to reflect async being used. The simple answer is that whenever you have a task that could potentially involve waiting, use async. Hopefully, your database queries won't take long enough to roundtrip to actually benefit much from async, but if your database falls down or is being hammered particularly hard, it'll at least help to not deadlock IIS in the process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With