Click here to Skip to main content
15,880,469 members
Articles / Web Development / ASP.NET
Tip/Trick

Asynchronous Programming in Web API /ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.69/5 (14 votes)
10 Aug 2014CPOL3 min read 146.5K   8   37   3
Asynchronous programming in Web API /ASP.NET MVC

Introduction

We know that from .NET 4.5 onwards, the feature of asynchronous programming has been implemented. The programming technique (with async and await keyword) is much easier than the old multi threading concept where developers need to implement multi threading on their hand. Actually the concept of multi threading performs in background but the async and await keywords have made a layer on it. Anyway, this article is not aimed at the multi threading concept but we will know how we can implement asynchronous programming concept on top of MVC framework, basically in Web API which is on top of MVC. We will use entity Framework 6.0 to manipulate data. Please keep in mind Entity Framework 6.0 onwards support asynchronous query in database, so make sure that you too are using at least Entity Framework 6.0. So, let’s start with a little theory and then we will implement in code. To implement asynchronous controller in MVC, we may inherit our controller class from AsyncController class. Please try to understand that I am saying we may need it, but it’s not mandatory. Let’s look into the AsyncController class. The AsyncController class is derived from Controller class.

Image 1

And here is the definition of AsyncController class. We are seeing that AsyncController class is pretty empty and nothing is there other than empty constructor.

Image 2

So, you may or may not inherit your controller class from AsyncController class to implement asynchronous programming. Ok, let’s create one Web API application and give reference of Entity Framework 6.0 or upper. Here, you can check version of Entity Framework by right clicking on reference and browse property.

Image 3

CRUD Operation in Asynchronous API Controller Using Entity Framework

So, let’s implement the actual code to perform CRUD operation asynchronously. We know that when we want to define any asynchronous method (action in context of MVC), we have to decorate with “async” keyword and in this example, we are returning object of HTTPActionResult wrapping by Task.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebAPI.Models;
using System.Data.Entity;

namespace WebAPI.Controllers
{
    public class UserController : ApiController
    {
        ApiSecurityEntities _db = new ApiSecurityEntities();

        public async Task<IHttpActionResult> Read()
        {
            var data = await _db.UserMaster.ToListAsync();
            return Ok(data);
        }
        public async Task<IHttpActionResult> Create(UserMaster user)
        {
            _db.UserMaster.Add(user);
            await _db.SaveChangesAsync();
            return Created<UserMaster>("api/User/"+ user.Id ,user);
        }

        public async Task<IHttpActionResult> Update(UserMaster user, int Id)
        {
            var record = await _db.UserMaster.Where(f => f.id == Id).FirstOrDefaultAsync();
            if (record != null)
            {
                record.name = user.name;
                record.userpassword = user.userpassword;
                record.UserRole = user.UserRole;
                await _db.SaveChangesAsync();
                return Ok();
            }
            return NotFound();
        }

        public async Task<IHttpActionResult> Delete(Int32 Id)
        {
             var record = await _db.UserMaster.Where(f => f.id == Id).FirstOrDefaultAsync();
             if (record != null)
             {
                 _db.UserMaster.Remove(record);
                 await _db.SaveChangesAsync();
                 return Ok();
             }
             return NotFound();
        }
    }
}

To use the asynchronous query, please give reference of using System.Data.Entity; namespace in application.

Inherit from AsyncController

As we mentioned, we can inherit from AsyncController too. In this example, we have inherited our controller class from AsyncController class. Have a look at the below code:

C#
public class AsyncTestController : AsyncController
{
    ApiSecurityEntities _db = new ApiSecurityEntities();

    public async Task<list> ReturnView()
    {
        return await _db.UserMasers.ToListAsync();
    }
}

Asynchronous Action in MVC

The concept of asynchronous implementation is very similar in MVC. We know that in MVC framework, we can return ActionResult when our controller class is derived from “Controller” class. In case of asynchronous implementation, we can wrap the ActionResult object by Task. Have a look at the below implementation.

C#
public class AsyncTestController : Controller
   {
       ApiSecurityEntities _db = new ApiSecurityEntities();
       public async Task<actionresult> ReturnData()
       {
           return  View("View", await _db.UserMasers.ToListAsync());
       }
   }

Here the ReturnData() action is decorated with async keyword and the ActionResult is wrapped by Task. Then we are returning view containing Model data which is fetching from database asynchronously using Entity Framework 6.0.

Conclusion

In this example, we have learned to implement asynchronous concept in MVC framework. As we know, asynchronous processing improves performances by running non- blocking thread in background, so it’s useful when the operation is more IO centric, not CPU centric. One best scenario to implement asynchronous programming is service call. In application, we call various services here and there. It will be great if we call multiple services in parallel to improve the response time of the application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
QuestionEntity Framework Pin
BallaviKrishna16-Dec-14 0:27
BallaviKrishna16-Dec-14 0:27 
QuestionMy vote is 5 Pin
AndriyZZ27-Oct-14 15:28
AndriyZZ27-Oct-14 15:28 
GeneralMy vote of 3 Pin
Veronica S. Zotali14-Sep-14 1:08
Veronica S. Zotali14-Sep-14 1:08 
QuestionAsync Repository methods ? Pin
Veronica S. Zotali14-Sep-14 1:04
Veronica S. Zotali14-Sep-14 1:04 
There are things I do not understand. For instance, eventhough, I understand what you are trying to do in the Presentation Layer, I don't understand the async concept on the repository methods :

await _db.SaveChangesAsync();
db.UserMaster.ToListAsync();
_db.UserMaster.Where(f => f.id == Id).FirstOrDefaultAsync();
etc

How are all those repository methods implemented? Could you upload the solution and demonstrate what happens in the repository layer?

Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.