In ASP.NET MVC controller action method receives data from a web request and passes the data to a view which then creates the HTML to be sent to the browser. Frequently the action method needs to get data from a database or web service in order to display it in a web page or to save data entered in a web page. In those scenarios it's easy to make the action method asynchronous: instead of returning an ActionResult object, you return Task<ActionResult> and mark the method with the async keyword. Inside the method, when a line of code kicks off an operation that involves wait time, you mark it with the await keyword.
Here is a simple action method that calls a repository method for a database query:
public ActionResult Index() { string currentUser = User.Identity.Name; var result = fixItRepository.FindOpenTasksByOwner(currentUser); return View(result); }
And here is the same method that handles the database call asynchronously:
public async Task<ActionResult> Index() { string currentUser = User.Identity.Name; var result = await fixItRepository.FindOpenTasksByOwnerAsync(currentUser); return View(result); }
Under the covers the compiler generates the appropriate asynchronous code. When the application makes the call to
FindTaskByIdAsync
, ASP.NET makes the FindTask
request and then unwinds the worker thread and makes it available to process another request. When the FindTask
request is done, a thread is restarted to continue processing the code that comes after that call. During the interim between when the FindTask
request is initiated and when the data is returned, you have a thread available to do useful work which otherwise would be tied up waiting for the response.