Friday, August 8, 2014

Asynchronous programming in Web API /ASP.NET MVC

We know that from .NET 4.5 onwards the feature of asynchronous programming has implemented. The programming technique (with async and await keyword) is much easier then old multi threading concept where developer need to implement multi threading on their hand.

Actually the concept of multi threading performs in background but the async and await keyword has made a layer on it. Anyway, this article is not aiming to 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 using at least Entity Framework 6.0


So, let’s start with 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’s not mandatory. Let’s look into AsyncController class. The AsyncController class is derived from Controller class.
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.


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 click on reference and browse property.



CRUD operation in Asynchronous API controller using Entity Framework 
So, let’s implement 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.

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 said , we can inherit from AsyncController too. In this example we have inherited our controller class from AsyncController class. Have a look on below code.


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

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


Asynchronous action in MVC
The concept of asynchronous implementation in 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 on below implementation.

 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 application.  

No comments:

Post a Comment