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