Synchronous vs. Asynchronous Request Handling

Synchronous

The requests in the system depend on some external resource like user request. When a request comes in, ASP.NET takes one of its thread pool threads and assigns it to that request. The request handler will call that external resource synchronously. This blocks the request thread until the call to the external resource returns. Eventually, that external resource call returns, and the request thread resumes processing that request. When the request is complete and the response is ready to be sent, the request thread is returned to the thread pool.

Asynchronous 

When a request comes in, ASP.NET takes one of its thread pool threads and assigns it to that request. This time the request handler will call that external resource asynchronously. This returns the request thread to the thread pool until the call to the external resource returns.

Async/Await in ASP.NET MVC

Async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).

“await” as an “asynchronous wait”. That is to say, the async method pauses until the awaitable is complete (so it waits), but the actual thread is not blocked (so it’s asynchronous).

awaitable can await the result of an async method that returns Task … because the method returns Task, not because it’s async.

So you can also await the result of a non-async method that returns Task

When should we use Async/Await method in ASP.NET MVC

It can use for any process as a required but especially for several independent long running operations.

Asynchronous action methods might be useful when amust n action perform several independent long running operations.

Example:

1) Service oriented programming ex. Web API.

2) Export to excel operation which are handling large data.

3) Back end operation which takes more time simultaneously.

Benefit for use Async/Await Method

  • They can make your application handle more users.

Most multi-user applications, such as web sites, use a thread for each user session. There are a lot of threads in the thread pool, but if lot of users try to access the site then they can run out, which in turn lead to blocking. Also there is a memory cost for each thread started. If you have requests that access an external resource such as a database or a web API then async  frees up the thread while it is waiting. This means you will use fewer threads, and so avoid reaching the maximum number of threads so quickly and use less memory as well.

  • You can process multiple I/O bound methods in parallel.

Suppose we have three operations which takes 300, 400 and 500 milliseconds. With the synchronous call, total response time would be slightly more than 1200 milliseconds. However, if the calls are made asynchronously (in parallel), total response time would be slightly more than 500 milliseconds, because that is the duration of longest task/operation.

  • You can make your interface more responsive to the user

If you have a request on a site that is slow you can make the site more responsive by starting the action asynchronously and returning to the user before the action has finished. There are some issues around handling errors if the asynchronous task fails, but for places where your application interfaces to an external system that is slow this can be worth the effort.

Limitation of async/await programming

  • Won’t be support old IDE.
  • Proper handing during programming cause throw a error for small mistake.
  • There are some issues around handling errors if the asynchronous task fails.

Code Sample

using System.Threading.Tasks;
 EmployeeEntities entity = new EmployeeEntities();
 // Get all employee
 public async Task<ActionResult> Index()
 {
 List<Employee> employeeList = await entity.Employees.ToListAsync();
 return View(employeeList);
 }
 //Create new employee page
 public ActionResult Create()
 {
 return View(new Employee());
 }

//Save new employee data
[HttpPost]
public async Task<ActionResult> Create(Employee emp) {

if (ModelState.IsValid)
{
entity.Employees.Add(emp);
await entity.SaveChangesAsync();
return RedirectToAction(“Index”);
}
return View(emp);
}

// Get employee details by id
public async Task<ActionResult> Details(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

Employee emp = await entity.Employees.FindAsync(id);
if (emp == null)
return HttpNotFound();

return View(emp);
}

// Edit employee details by id page
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

Employee emp = await entity.Employees.FindAsync(id);
if (emp == null)
return HttpNotFound();

return View(emp);
}

//Save updated employee details
[HttpPost]
public async Task<ActionResult> Edit(Employee emp)
{

if (ModelState.IsValid)
{
entity.Entry(emp).State = EntityState.Modified;
await entity.SaveChangesAsync();
return RedirectToAction(“Index”);
}
return View(emp);
}

//Delete employee by id
[HttpPost]
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

Employee emp = await entity.Employees.FindAsync(id);
if (emp == null)
return HttpNotFound();

entity.Employees.Remove(emp);
await entity.SaveChangesAsync();
return RedirectToAction(“Index”);
}

 For long running operations:

void MyMethod() { // Do synchronous work. Thread.Sleep(1000); } async Task MyMethodAsync()ss { // Do asynchronous work. await Task.Delay(1000); }

Author

  • Sunil Kumar

    Sunilkumar works as Sr. Software Engineer with Trigent Software. With nearly eight years of experience in .NET technologies, Sunil has strong expertise in ASP .NET, C#, VB .NET, SQL Server, My SQL 5.0, jQuery/JavaScript, MVC, Telerik Tool, WCF and so forth.