Skip to content

Converting a Controller Method in MVC5 to async

Updated: at 09:24 PM

I’m currently working on a Pluralsight course on ASP.NET and I have to admit I’m slow to adopt async methods in my code because it feels a little complex when non-async code is what I’m use to.  I’m feeling like since I’m doing this Pluralsight course I should really show best practices and clearly async controller methods is no doubt a best practice.

I’m surprised it was actually so easy.  First, let me show you the code that I had written that is not async that I’m sure you are all familiar with.

public ActionResult Index()
{
    using (var context = new MultiTenantContext())
    {
        var speakers = Utils.FilterSpeakersByTenant(context.Speakers.ToList(), Tenant.Name);
    foreach (var speaker in speakers)
    {
        speaker.ImageUrl = $"/Content/Images/Speakers/Speaker-{speaker.PictureId}-75.jpg";
        var sessions =
            speaker.Sessions.
                Where(a => a.TenantName == Tenant.Name).
                OrderBy(a => a.Title).ToList();
        speaker.Sessions = sessions;
    }
    return View("Index", "_Layout", speakers);
}

}

All I had to change (besides adding the async name space for Task) was to have speakers return a task with the ToListAsync method and change the signature of the method to return a task. Here is the updated code that is now fully async.

public async Task Index()
{
    using (var context = new MultiTenantContext())
    {
        var speakers = await context.Speakers.ToListAsync();
        foreach (var speaker in speakers)
        {
            speaker.ImageUrl = $"/Content/Images/Speakers/Speaker-{speaker.PictureId}-75.jpg";
            var sessions =
                speaker.Sessions.
                    Where(a => a.TenantName == Tenant.Name).
                    OrderBy(a => a.Title).ToList();
            speaker.Sessions = sessions;
        }
        return View("Index", "_Layout", speakers);
    }
}