Skip to main content

Asynchronous actions in ASP.NET

An asynchronous operations become very popular in modern programming because by using its developers can take full advantage of multicore processors and perform several operation at the same time. Multithreding exists in ASP.NET since 2.0 version but it was very sophisticated to use it. However starting from .NET 4.5, ASP.NET is fully compatible with all these great features.

To demonstrate how to start with the asynchronous operation in ASP.NET 4.5 I`ve created very simple solution which consist of three projects (Picture 1.):
  • AsyncPageService - REST service based on a ApiController; provides function which will be called by the website.
  • AsyncPageWebsite - main ASP.NET website.
  • Contracts - contains shared type between service and website.

Picture 1. Solution projects.
In my solution data is served by very simple REST web service, which is build by using ApiController from ASP.NET MVC. Inside this I`ve created two controllers (first return N random integers and the second return hardcoded list of an Contracts.User - which is shared type from an Contracts library)  for a GET  requests and decided to stay with a default service configuration so response format (XML or JSON) relay on header 'accept' value with XML by default. Below I presented action for generating random N random numbers - where N is determined by input function parameter with default value equals to 10.

Code Snippet
  1. namespace RestApi.Controllers
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Collections.ObjectModel;
  6.     using System.Web.Http;
  7.  
  8.     using System.Web.Mvc;
  9.     using MVC = System.Web.Mvc;
  10.  
  11.     public class RandomController : ApiController
  12.     {
  13.         public List<int> GetRandomNumbers(int count = 10)
  14.         {
  15.             var result = new List<int>();
  16.             var random = new Random();
  17.             var tempRandom = 0;
  18.  
  19.             for (var i = 0; i < count; i++)
  20.             {
  21.                 tempRandom = random.Next(0, 32);
  22.                 result.Add(tempRandom);
  23.             }
  24.  
  25.             return result;
  26.         }
  27.     }
  28. }


After  web services is ready it`s time to present how we can use it. To demonstrate working code I`ve created a Default.aspx page and put all logic in Page_Load function. This function has additional keyword 'async' in the function signature because it needs to working with asynchronous calls. Inside that function body firstly HTTP client has been created to allow communication between web service and website. Secondly, to return JSON format from web service accept header need to be set to "application/json". Later in the code both endpoints are called by using build in asynchronous function GetStringAsync (JSON is always a string) - return type of the both calls is Task type. Next we need to wait until both until task complete and this functionality is provided by a built-in Task.WhenAll function with await keyword - code will block in this line until both task finish. When both requests completed results of the tasks need to be deserialized to a proper objects type by using DeserializeObject extension function and target types will be use as DataSource for the a page controls.

Last thing that needs to be done in Default.aspx is setting a new page property Async="true" to notify ASP.NET that page might handle asynchronous calls.

Code Snippet
  1.  
  2. namespace AsyncPageWebsite
  3. {
  4.     using Contracts;
  5.     using System;
  6.     using System.Collections.Generic;
  7.     using System.Diagnostics;
  8.     using System.Net.Http;
  9.     using System.Threading.Tasks;
  10.  
  11.     public partial class Default : System.Web.UI.Page
  12.     {
  13.         private HttpClient client;
  14.  
  15.         protected async void Page_Load(object sender, EventArgs e)
  16.         {
  17.             // Creating HTTP Client for handling requests.
  18.             this.client = new HttpClient();
  19.  
  20.             // Setting return type from web service to JSON format.
  21.             this.client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  22.  
  23.             // Calling both services in asynchonous actions.
  24.             var getTeenRandomResultTask= this.client.GetStringAsync("http://localhost/AsyncPageService/api/random");
  25.             var getUsersListStringTask = this.client.GetStringAsync("http://localhost/AsyncPageService/api/user");
  26.  
  27.             // Wait until all task finish.
  28.             await Task.WhenAll(getTeenRandomResultTask, getUsersListStringTask);
  29.  
  30.             // Deserializing strings from tasks results.
  31.             var teenRandomResultList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(getTeenRandomResultTask.Result);
  32.             var userList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(getUsersListStringTask.Result);
  33.  
  34.             // Bind IEnumerable types to the proper controls.
  35.             rRandomNumbers.DataSource = teenRandomResultList;
  36.             gvUsers.DataSource = userList;
  37.  
  38.             // Call the DataBind for whole page - cause call DataBind for each control on page.
  39.             this.DataBind();
  40.         }
  41.     }
  42. }

Thank you.

Source code is available here.

Read more:



Popular posts from this blog

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition...

Creating common partial class with Entity Framework

When we use the Entity Framework (EF) in multilayer information systems sometimes we want to extend classes generated by EF by adding some common properties or functions. Such operation can`t be conduct on *.edmx data model so we need to make some improvement in our solution. Let`s begin... Lets assumed that in our soulution we have only three layer (three project): Client console application which has reference to the second layer  - ' ConsoleApplication ' project name Class library project with class interfaces only - ' Interfaces ' project name Class library class implementation and data model referenced to 'Interfaces' project - ' Classes ' project name. Picture 1. Solution structure. Now when we have all solution structure we can focus on data model. In the ' Classes ' project we create a new folder named ' Model ' and inside add new item of ADO.NET Entity Data Model named ' Learning.edmx ' - it may be empty ...

Using Hortonworks Hive in .NET

A few months ago I decided to learn a big data. This sounds very complex and of course it is. All these strange names which actually tells nothing to person who is new in these area combined with different way of looking at data storage makes entire topic even more complex. However after reading N blogs and watching many, many tutorials today I finally had a chance to try to write some code. As in last week I managed to setup a Hortonworks distribution of Hadoop today I decided to connect to it from my .NET based application and this is what I will describe in this post. First things first I didn`t setup entire Hortonworks ecosystem from scratch - I`d love to but for now it`s far beyond my knowledge thus I decided to use a sandbox environment provided by Hortonworks. There are multiple different VMs available to download but in my case I`ve choose a Hyper-V. More about setting this environment up you can read here . Picture 1. Up and running sandbox environment. Now whe...