Async task in Asp.net MVC Example

Here is how to write Asynchronous method, an Async await example in Asp.net MVC.

What is Asynchronous programming?
Asynchronous programming is writing code in a way that will allow multiple things to occur in application at the same time without blocking the GUI, or waiting for other task to complete.

When do we need Asynchronous calls?

Asynchronous calls are required for any long running task, think of a task that will Fetch 10000 records from database and send customized email to each user

Required namespace
using System.Threading;       
using System.Threading.Tasks;

Notice some keywords like async, await , task

First we write few time taking tasks, here just to create some time gap we have added await Task.Delay(1000), but in real life you need to write actual code to fetch data from database, sending emails etc.

Async await in Asp.net MVC

public async Task<int> LongTask1()
{
        await Task.Delay(1000);
        return 50;
}
public async Task<string> LongTask2()
{
        await Task.Delay(1000);
        return "WTR Test";
}
           
public async Task<int> LongTask3()
{
        await Task.Delay(1000);
        return 50;
}
Async ActionResult

Now if we want all above task to be completed before we want some other action to happen, then we can combine them all with “WhenAll” method

now call all above task from an ActionResult

public async Task<ActionResult> Index() 
{
Task[] taskArray = new Task[3]; 
taskArray[0] = LongTask1();
taskArray[1] = LongTask2();
taskArray[2] = LongTask3();
// Now, we await them all.
await Task.WhenAll(taskArray);
return View(); 
}

Even though all task will take some time to complete, but our GUI will remain free to do additional task

Alternatively, if we want any of above tasks completed, then some action should happen, then we use “WhenAny” method.

public async Task<ActionResult> Index() 
{
    Task[] taskArray = new Task[3]; 
    taskArray[0] = LongTask1();
    taskArray[1] = LongTask2();
    taskArray[2] = LongTask3();
    await Task.WhenAny(taskArray);
return View(); 
}

We have multiple waiting options with task

  • await task

    Wait/await for a task to complete
    Get the result of a completed task

  • await Task.WhenAny

    Wait/await for one of a collection of tasks to complete

  • await Task.WhenAll

    Wait/await for every one of a collection of tasks to complete

  • await Task.Delay

    Wait/await for a period of time

  • Task.Run

    Set the Task on queue to run on threadPool

Async ActionResult in Asp.net MVC

Here we define an Async ActionResult in Asp.net MVC and learn how to work with async,await, Delay.
Following ActionResult are written in public class aspnetmvcController : Controller

// this is normal ActionResult
public ActionResult asynctask()
{
    return View();
}
// Here is how we make that async ActionResult
public async Task<ctionResult> asynctask()
{
    await Task.Delay(10);
    return View();
}

Now let's try to fetch some data asynchronously from database of any other data source to display on our page, so the goal is to keep the page free while data is loading, user should be able to click on other links freely.

public async Task<ActionResult> asynctask()
{
List<blogObj> blogList = await Task.Run(() => CFD.GetBlogList(Server.MapPath("~/configs/homepage.xml")));
         
ViewBag.BlogList = blogList;
            
await Task.Delay(10);
return View();
}

We should avoid writing Task.Delay(10), that actually blocks the UI, and instead of passing the list through ViewBag, we can directly pass the value to model, so the same above code can be written better way like below.

public async Task<ActionResult> asynctask()
{
List<blogObj> blogList = await Task.Run(() => CFD.GetBlogList(Server.MapPath("~/configs/homepage.xml")));
          
return View("asynctask", await Task.FromResult(blogList));
}

We also can return the whole view as async, just think of situation where you have model with other properties and you want to return the whole view asynchronously.

public async Task<ActionResult> index()
{
             
    return await Task.Run(() => View());
} 

Notice await Task.Run(() => DataSourceMethodName())

Here is another real-time example of how you can read web content asynchronously in Asp.net MVC application.

public async Task<string> getwebcontent()
{
HttpClient hc=new HttpClient();
string _responseresult;
string _url="https //www.webtrainingroom.com";
    var _tmessage=await hc.GetAsync(_url);  
         
    _responseresult = await _tMessage.Content.ReadAsStringAsync();
    return _responseresult;
}
Call Async Method from Razor View

There is another efficient approach of loading data asynchronously, you can directly call async service method in your razor view, for example i want to display student list from database or some async service, here are simple step can make much cleaner approach.

Create an until class, write a async method that will return student list or array , then call the util method from razor view.

In below example i am loading student list from database, (you can call any other API in same place), Call Async Method from Razor View.

public class Util
{
   public static async Task<List<Student>> GetStudents()
        {
            List<Student> students = new List<Student>();
            Student s;
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlDataAdapter da = new SqlDataAdapter("select * from tbStudent", con);
            da.Fill(dt);
            foreach (DataRow row in dt.Rows)
            {
                s = new Student();
                s.StuId = Convert.ToInt32(row["StuId"]);
                s.FirstName = row["Firstname"] as string;
                s.LastName = row["Lastname"] as string;
                s.Email = row["Email"] as string;
                s.Mobile = row["ContactNumber"] as string;
                students.Add(s);
            }
            return await Task.FromResult(students);
        }
}

Now, in razor view simply call the method like below.

List<Student> students = await Util.GetStudents();

You probably should check if the students variable is not null, then start processing..

Note: instead of returning student list object I could return the DataTable asynchronously, like Task.FromResult(dataTableObject), so if you are using ado.net objects, nothing to worry! Only additional task will be remembering each field name while rendering in razor.

You should also read Async Await C# Example (in Console Application)

 
Async task in Asp.net MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial