Starting from .NET 4.5 ASP.NET MVC supports async/await for the action methods on your controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<ActionResult> MyReallySlowReport() | |
{ | |
List<ReportItem> items; | |
using (ApplicationDbContext context = new ApplicationDbContext()) | |
{ | |
items = await context.ReportItems.ToListAsync(cancellationToken); | |
} | |
return View(items); | |
} |
Something I wasn’t aware of until I saw this blog post that is possible to cancel an async requests on the server. I knew it was possible to cancel an AJAX request on the client but I didn’t know that this cancellation will be forwarded to the server. I thought that on the server the request continued but that the result was discarded.
What you have to is to add a CancellationToken as an extra parameter to your action method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<ActionResult> MyReallySlowReport(CancellationToken cancellationToken) | |
{ | |
List<ReportItem> items; | |
using (ApplicationDbContext context = new ApplicationDbContext()) | |
{ | |
items = await context.ReportItems.ToListAsync(cancellationToken); | |
} | |
return View(items); | |
} |