Leveraging the Power of Asynchrony in ASP.NET

Asynchronous programming has had a lot of attention in the last couple of years and there are two key reasons for this: First it helps in providing a better user experience by not blocking the UI thread which avoids the hanging of the UI screen until the processing is done and second, it helps in scaling up the system drastically without adding any extra hardware.

But writing asynchronous code and managing the thread gracefully was a tedious task. But as the benefits are tremendous.. Read complete post on Infragistics blog

Advertisement

Asynchronous programming with async and await : explained

In one of my previous posts, I discussed about the synchronous and asynchronous programming model. We saw in details that how does it work in single and multi-threaded mode. This post is extension of that post and here we are going to discuss the two relatively new keyword async and await and how does that actually work. I got many questions around this so sharing it in details here. If you are not very clear about how synchronous and asynchronous programming works and how does it work in single and multi-threaded scenario then refer my previous post mentioned below.

Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Continue reading

Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Recently, I was speaking in an event and I asked a question about Asynchronous programming to the audience, I found that many were confused between multi-threading and asynchronous programming and for few, it was same. So, I thought of explaining these terms including an additional term Concurrency. Here, there are two completely different concepts involved, First – Synchronous and Asynchronous programming model and second – Single threaded and multi-threaded environments. Each programming model (Synchronous and Asynchronous) can run in single threaded and multi-threaded environment. Let’s discuss each in detail.

Synchronous Programming model – In this programming model, A thread is assigned to one task and starts working on it. Once the task completes then it is available for the next task. In this model, it cannot leave the executing task in mid to take up another task. Let’s discuss how this model works in single and multi-threaded environments.

Single Threaded – If we have couple of tasks to be worked on and the current system provides just a single thread, then tasks are assigned to the thread one by one. It can be pictorially depicted as

singlethreadedHere we can see that we have a thread (Thread 1 ) and four tasks to be completed. Thread starts workingon the tasks one by one and completes all. (The order in which tasks will be taken up, does not affect the execution, we can have different algorithm which can define the priorities of tasks)

Continue reading

Writing Asynchronous Web Pages with ASP.NET- Part 2

This is the second part in the series of Writing Asynchronous web pages in ASP.NET. In my last post, we discussed about various programming model for writing asynchronous code and wrote a asynchronous page using Asynchronous Programming model(APM). The link of part-1 of the series is given below

Writing Asynchronous Web Pages with ASP.NET- Part 1

In this post we’ll use another approach that is Event-based asynchronous pattern(EAP).

What is Event-based asynchronous Pattern (EAP)?

This model provides another way to write asynchronous code. In this pattern, it provides one void method (as a naming convention method name ends with async) and one or more events to notify the caller that there is a change in status. It means we don’t need to keep checking the status of the task, an event will be raised once the task will be completed. This asynchronous task runs in the background and simplest one, uses BackgroundWorker class to implement.

Any class that provides the capability to call its method asynchronously (using EAP model), provides a method that ends with async (naming convention) and an event that notifies when the task completes. It can provide more events to provide the status of the thread. We should follow these rules in our class if we want to write our own custom asynchronous methods that uses EAP Model.

So let’s create a class that uses this pattern

public class MyCustomClass
{
    public void ReadCharCountAsync(byte[] buffee, int offset, int count);
    public event ReadCompletedEventHandler ReadCompleted;
}

public delegate void ReadCompletedEventHandler(object sender, ReadCompletedEventArgs readCompletedEventArgs);

public class ReadCompletedEventArgs : AsyncCompletedEventArgs
{
    public int Result { get; }
}

We can see here that my class has one async method and one event handler. Then we defined the event handler and event arguments which contains the result of the method.

In this post, I’ll be using a .NET class WebClient that provides a method that can consumed asynchronously using EAP model. In this example, I am just downloading a page from the given URL and showing it on the screen. There could be many other scenarios.

I have created a webpage and put Async=”true” in the page directive in aspx file. This tells the page that this will be executed asynchronously. So let’s see the code behind

public partial class AsyncEAP : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            WebClient client = new WebClient();
            Uri uri = new Uri("http://www.google.com/");

            // Specify that the DownloadStringCallback method gets called
            // when the download completes.
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
            client.DownloadStringAsync(uri);
        }

        void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                renderedItem.InnerHtml = e.Result;
            }
        }
    }

So if we see the above code then we see that in Page_Load method after creating the instance of WebClient, I have subscribed the completed event and then called the DownloadStringAsync method. DownloadStringCallback method gets called once the download completes. Here I just checked if there is an error while executing and if there is no error then accessed the result. Here there is no way to find the status of the task but sure that once the method completes its processing, the completed event handler will be fired.

There are many other classes that provides the async feature using this model and we can use that. In my next post, We’ll use Task based asynchrony and see how can we leverage that in our ASP.NET pages.

Cheers,
Brij