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

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileSt...

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...

Using Newtonsoft serializer in CosmosDB client

Problem In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB.  Solution In CosmosDBV3 .NET Core API, when creating an instance of  CosmosClient one of optional setting in  CosmosClientOptions is to specify an instance of a Serializer . This serializer must be JSON based and be of  CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from  CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex.  For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from  CosmosSerializer.  using  Microsoft.Azure.Cosmos; using  Newtonsoft.Json; usin...