Asynchronous actions
What are asynchronous actions?
The ASP.NET MVC Controller class in combination .NET enables you to write asynchronous action methods that return an object of type Task
. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task
and ASP.NET MVC supports Task.
What are tasks?
Tasks are represented by the Task type and related types in the
System.Threading.Tasks
namespace.The .NET Framework builds on this asynchronous support with the
await
andasync
keywords that make working withTask
objects much less complex than previous asynchronous approaches.The
await
keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code.The
async
keyword represents a hint that you can use to mark methods as task-based asynchronous methods.The combination of await, async, and the Task object makes it much easier for you to write asynchronous code in .NET
The new model for asynchronous methods is called the Task-based Asynchronous Pattern (TAP)
Choosing Synchronous or Asynchronous Action Methods
In general, use synchronous methods for the following conditions:
The operations are simple or short-running.
Simplicity is more important than efficiency.
The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.
In general, use asynchronous methods for the following conditions:
You're calling services that can be consumed through asynchronous methods, and you're using .NET 4.5 or higher.
The operations are network-bound or I/O-bound instead of CPU-bound.
Parallelism is more important than simplicity of code.
You want to provide a mechanism that lets users cancel a long-running request.
Testing shows that the blocking operations are a bottleneck in site performance and that web servers can service more requests by using asynchronous methods for these blocking calls.
Blocking operations are a bottleneck in site performance and that web servers can service more requests by using asynchronous methods for these blocking calls.
Let's make our controllers asynchronous
In case we wanted to implement an asynchronous Create() action method we would be looking into the following changes:
Asynchronous version of Add method in the fake context
Asynchronous version of create action method in movies controller
Note
We are also using IActionResult
interface instead of ActionResult
class which is very much valid in object-oriented programming, given that an interface can also be used as a type!
Last updated