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.):
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.
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.
Thank you.
Source code is available here.
Read more:
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. |
Code Snippet
- namespace RestApi.Controllers
- {
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Web.Http;
- using System.Web.Mvc;
- using MVC = System.Web.Mvc;
- public class RandomController : ApiController
- {
- public List<int> GetRandomNumbers(int count = 10)
- {
- var result = new List<int>();
- var random = new Random();
- var tempRandom = 0;
- for (var i = 0; i < count; i++)
- {
- tempRandom = random.Next(0, 32);
- result.Add(tempRandom);
- }
- return result;
- }
- }
- }
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
- namespace AsyncPageWebsite
- {
- using Contracts;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Net.Http;
- using System.Threading.Tasks;
- public partial class Default : System.Web.UI.Page
- {
- private HttpClient client;
- protected async void Page_Load(object sender, EventArgs e)
- {
- // Creating HTTP Client for handling requests.
- this.client = new HttpClient();
- // Setting return type from web service to JSON format.
- this.client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- // Calling both services in asynchonous actions.
- var getTeenRandomResultTask= this.client.GetStringAsync("http://localhost/AsyncPageService/api/random");
- var getUsersListStringTask = this.client.GetStringAsync("http://localhost/AsyncPageService/api/user");
- // Wait until all task finish.
- await Task.WhenAll(getTeenRandomResultTask, getUsersListStringTask);
- // Deserializing strings from tasks results.
- var teenRandomResultList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(getTeenRandomResultTask.Result);
- var userList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<User>>(getUsersListStringTask.Result);
- // Bind IEnumerable types to the proper controls.
- rRandomNumbers.DataSource = teenRandomResultList;
- gvUsers.DataSource = userList;
- // Call the DataBind for whole page - cause call DataBind for each control on page.
- this.DataBind();
- }
- }
- }
Thank you.
Source code is available here.
Read more:
- http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45
- http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx