Basic Concept Of Async And Await In ASP.NET MVC

Here, we are going to study about Async and Await which are the most confusing keywords for the developers. What they actually meant and why we should use it.

So let’s get started to understanding this stuff.

So What is meant by Asynchronous Programming?

It is the only way which allows us to write code that allows several things to execute at the same time without blocking any other process or waiting for other processes to complete. This is completely different from synchronous programming in which all things happen in the order they are written.

Example of Synchronous Method

public string Name()
{
       Thread.Sleep(4000);
       return "Faisal Pathan";
}

This method is synchronous and will take 4000ms to execute as we have specified the sleep time for 4000ms. Until it get completed no other task can be performed.

Example of Asynchronous Method

public async Task<string> NameAsync()
{
      await Task.Delay(4000);
      return "Faisal Pathan";
}

How to make method Async?

  • Mark the method as async which will tell the compiler that the method is asynchronous.
  • We used the await keyword which tells the compiler that we want the result for the task.
  • We changed the return type as Task<string>

Lets us understand this in a better way with multiple examples.

Create a class as DemoMethods.cs

using System.Threading;
using System.Threading.Tasks;

namespace AsyncAndAwait.Models
{
    public class DemoMethods
    {
        public string Content()
        {
            Thread.Sleep(3000);
            return "Synchronous Method";
        }

        public int Count()
        {
            Thread.Sleep(6000);
            return 10;
        }

        public string Name()
        {
            Thread.Sleep(4000);
            return "Faisal Pathan";
        }
        public async Task<string> ContentAsync()
        {
            await Task.Delay(3000);
            return "Asynchronous Method";
        }

        public async Task<int> CountAsync()
        {
            await Task.Delay(6000);
            return 10;
        }

        public async Task<string> NameAsync()
        {
            await Task.Delay(4000);
            return "Faisal Pathan";
        }
    }
}

Now we will call the synchronous methods and asynchronous methods from different methods and will see the time taken to execute it.

using AsyncAndAwait.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace AsyncAndAwait.Controllers
{
    public class HomeController : Controller
    {
        
        [HttpGet]
        public ActionResult Index()
        {
            Stopwatch watch= new Stopwatch();
            watch.Start();
            DemoMethods methods = new DemoMethods();
            var content = methods.Content();
            var count = methods.Count();
            var name = methods.Name();
            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            DemoMethods methods = new DemoMethods();
            watch.Start();
            var contentTask = methods.ContentAsync();
            var countTask = methods.CountAsync();
            var nameTask = methods.NameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;
            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }
    }
}

Change the Layout file to this.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Call Synchronous Method", "Index", "Home")</li>
                    <li>@Html.ActionLink("Call Asynchronous Method", "IndexAsync", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Change the View -> Home -> Index.cshtml file also

@{
    ViewBag.Title = "Home Page";
}

<h2>Time take @ViewBag.WatchMilliseconds</h2>

Output:

basic-concept-of-async-and-await-in-asp-net-mvc-1

basic-concept-of-async-and-await-in-asp-net-mvc-2

You can download the source code from here

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories