The working of Asynchronous Handler can be shown as



As we know if we need to create a normal custom HTTPHandler. We need to implement
IHTTPHandler interface and if we want to create a custom Asynchronous HTTPHandler, we need to implement IHttpAsyncHandler.

In this post, I will be discussing, How we can write Asynchronous HTTPHandlers with the help of new features introduced in .NET 4.5 framework.


In the example, I’ll create an asynchronous HTTPHandler with the help of asp.net 4.5 that downloads rss feed.


To create Asynchronous HTTPHandler in asp.net 4.5, we need to implement the method
ProcessRequestAsync of new abstract class HttpTaskAsyncHandler that got newly introduced.

For that I created a class library named
AsyncHandlerLibrary , which has a Handler class CustomAsyncHandler which implements HttpTaskAsyncHandler.

So the class CustomAsyncHandler will be as


public class CustomAsyncHandler : HttpTaskAsyncHandler
 {

    public override async Task ProcessRequestAsync(HttpContext context)
    {
        string url = context.Request.QueryString["rssfeedURL"];
        if (string.IsNullOrWhiteSpace(url))
        {
           context.Response.Write("Rss feed URL is not provided");
        }
        WebClient webClient = new WebClient();

        //It starts downloading the rss asynchronously and the asp,net thread become free
        //and become available in threadpool
        //once the the it load the rssfeed loading completes it get assigned to another ASP.NET thread from the threadpool
        var rssfeed = await
            webClient.DownloadStringTaskAsync(url);

        // Writing the rss on the screen
        context.Response.Write(rssfeed);
    }

     public override bool IsReusable
     {
         get { return true; }
     }

     public override void ProcessRequest(HttpContext context)
     {
         throw new Exception("The ProcessRequest method has no implementation.");
     }

}

Now if you see the above code, I have implemented
ProcessRequestAsync , in which I read the rss url from query string. And asynchronously downloaded the rss feed and later wrote it in response.

Now you can see, with help of new keywords async keyword and await operator of .NET 4.5, it is extremely easy to write asynchronous code. It also got ensured that same can be used in asp.net with the introduction of new APIs.

Now build the project and add the reference in your web application. Also add this in your web.config file as

<system.webServer>
  <handlers>
     <add name="myHandler" verb="*" path="*.rss" type="AsyncHandlerLibrary.CustomAsyncHandler"/>
  </handlers>
</system.webServer>

Then run your application.
Now you can see it has never been so easy to write Asynchronous HTTPHandler. Now enjoy coding with ASP.NET 4.5.