Learn About Asynchronous HTTP Modules and HTTP Handlers in Asp.Net 4.5

In Asp.Net 4.5 asynchronous HTTP Handlers and Modules can be created with ease at the same time with less code complexity. In this article I will explain about the advantages of introducing asynchrony on the HTTP Pipeline and creating them in Asp.Net 4.5.

A Background on HTTP Module and HTTP Handler

HTTP Modules are the components in the Asp.Net HTTP request pipeline that interrupt all the incoming Asp.Net requests. Operations like setting up cookies, logging, authentication verification, etc., can be done using them.

HTTP Handlers are the final destination of the incoming web requests and they are responsible for processing the request and sending back the response. For example .aspx requests are processed and the response HTML is sent back to the browser by PageHandlerFactory class.

How Asynchronous Processing Gets the Edge?

In a synchronous Asp.Net request processing, there are two thread pools that take part:

  1. Asp.Net thread pool (Threads for processing the main request)
  2. I/O thread pool (Threads for performing the I/O operations – File, Database, Network, etc.)

When an Asp.Net request comes in, the request is handed over to an Asp.Net thread pool thread and the same thread takes care of processing the request and sending back the response. In the mid, if any IO related operation is performed then that job is handed over to a thread from the I/O thread pool. Note that the main Asp.Net thread pool thread will wait until the I/O thread operation is complete. This results in a blockage of the main asp.net thread. This would adversely result in the other incoming requests having to wait in the queue if the asp.net thread pool does not have any free threads to be picked up.

In an asynchronous request processing, blocking of the main thread during I/O operations can be avoided because the main Asp.Net thread pool thread will be returned back to the thread pool once the I/O operation is initiated so that it could be used by the other incoming asp.net requests. Once the I/O operation completes then it will hand over the rest of the processing to another thread from the Asp.Net thread pool. This is where you get the edge. You should decide wisely on when and where to introduce the asynchrony in Asp.Net request processing.

In summary:

  1. No blockage of the asp.net thread during an external operation.
  2. More availability of the asp.net thread pool threads.

Creating Asynchronous HTTP Module and HTTP Handler in Asp.Net 4.5

Though the previous versions of Asp.Net allowed the creation of asynchronous HTTP modules and HTTP handlers, with the introduction of Task in .net 4.0, and async / await keywords in the .net 4.5 framework, it has become much simpler. In this section I will show you about creating Asynchronous HTTP module and handler.

Create an Asp.Net 4.5 empty web application to which we will be adding the asynchronous HTTP module and handler.

Asynchronous HTTP Module

Create a class named MyAsyncHttpModule.cs and inherit from the interface IHttpmodule. In the Init event make use of the class EventHandlerTaskAsyncHelper offered by .net framework 4.5 to tie the Async method, which is going to perform an I/O operation. Below is the sample code for Async Http Module.

namespace AsyncModulesAndHandlers
{
    public class MyAsyncHttpModule: IHttpModule
    {
        #region IHttpModule Members
 
        public void Dispose()
        {
        }
 
        public void Init(HttpApplication context)
        {
            EventHandlerTaskAsyncHelper taskAsyncHelper = new EventHandlerTaskAsyncHelper(LogMessage);
            context.AddOnPostAuthorizeRequestAsync(taskAsyncHelper.BeginEventHandler, taskAsyncHelper.EndEventHandler);
        }
 
        private async Task LogMessage(object sender, EventArgs e)
        {
            //Processing will be handed over to the I/O thread.
            using (StreamWriter streamWriter = new StreamWriter("/Logs/RequestLogs.txt", true))
            {
                string logText = String.Format("The page requested is: {0}\nRequested at: {1}", ((HttpApplication)sender).Context.Request.RawUrl, DateTime.Now);
                //Main Asp.Net thread will return back to the thread pool and will not wait for the process complete.
                //Once the I/O operation is complete then the EndEventHandler will be taken care by a new thread from the Asp.Net thread pool.
                await streamWriter.WriteLineAsync(logText);
            }
        }
 
        #endregion
    }
}

Asynchronous HTTP Handler

Create a class file named MyAsyncHttpHandler.cs. Derive it from the .net 4.5 abstract class and implement the method ProcessRequestAsync. Here you can make use of the async and await keywords to make asynchronous operations. Below is the sample code.

namespace AsyncModulesAndHandlers
{
    public class MyAsyncHttpHandler : HttpTaskAsyncHandler
    {
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            string responseData = await GetDataFromDatabaseAsync();
            context.Response.Write(responseData);
        }
 
        private async Task<string> GetDataFromDatabaseAsync()
        {
            //Consider this operation is reading the response data from the database (as IO operation).
            string value = "Consider it as data from DB!!";
            return value;
        }
    }
}

Happy reading!



Related Articles

Comments

  • Cheap Oakley Unfaithful online store

    Posted by jhkirfibq on 06/24/2013 02:48pm

    Fake Ray Bans ,Oakley sunglasses are building a new trend inside fashion world. Independent status within the fashion field, and so are creating some exciting products, modifications to trends as a way to advance while using times. A shift from sports gear sunglasses, super-polished and chic Armani superb range of a different style just included in the collection. Replica Oakley Sunglasses ,Oakley sunglasses will almost allways be leading in the field of science, for the reason that by using high-tech, faster and better preventive effect. Fashion: considering stylish Oakley sunglasses manufacturer usually is: pilot Oakley sunglasses, clip cups, lens tilt, flip Oakley sun's shadow copy Oakley sun glasses. Oakley Mens ,Will be difference between and ordinary OAKLEY sunglasses discount? This is a number of sizes, shapes and designs to exhibit off your attitude, talking to you, and to echo your personality. How to protect their eyes? The answer then is in glasses. Select the sunglasses, in addition to the sunglasses can look after the eyes, it a fashion and lifestyle. Comfortable like a pair of modest sunglasses sunglasses several dark lens held by way of framework, to be able to maintain within the Gulf harmful rays, which is not a way to this effect. Oakley can be an entertainment brand, however the men and women can also experience an affordable price, this can be a very good variety. Oakley shades will often be put on the application of tools including drills or saws to counteract harmful eye flight particle. Naturally, this really is merely a basic standard, a choice of specific sunglasses, we could here is another more intuitive strategy to see the the greatest results. Should you be able to produce a business, then this courage to start out making the initiative, but make sure you did very meaningful. The durable anti-allergy frame three-dimensional metal sculpture and built ultra-light titanium, to ensure any weather or light conditions, and cozy sunglasses. Fashion sports sunglasses lenses the PLUTONITE manufacturing materials, together with 100% of harmful UV blocking blue light along with the polarization of Oakley sunglasses, ANSI industrial standards compared to U.S. specification of sharp-sightedness. These sunglasses are a great complement to, Jewelry, a web based retailer inventory of Oakley sunglasses, celebrities options, so they really provided inside most competitive budget.

    Reply
  • the cheapest clarisonic pro with consistency scrub purchasing in the ebay

    Posted by iouwanzi on 06/06/2013 06:20pm

    [url=http://www.miaclarisonicaustralia.org/clarisonic-classic]clarisonic classic[/url] Ce redressement en termes de fer relèvent de 4 modèles. Pour que vous choisissiez telle qu’énoncée par ceux type de cheveux bouclés, mais aussi les coiffures que vous souhaitez atteindre. Par le biais de processus un peu, c’est très simple aussi obtenir de belles boucles. Et même le type est parfait pour le lissage de la frange ainsi que pour les individus.Espagne, GHD annonce une promotion très utile. Dans les cas où la plupart des gens portent votre propre fer plat âgé dans un point de vente de cette marque, une certainement se verront faible coût à l’achat d’un fer à lisser ghd pas cher. Il est généralement valable jusqu’au 6 mai 2011. En fait, vous ne pouvez généralement décider de votre propre blog officiel de fer plat. Certaines personnes offrent le monde entier !Comme que je quitterai les gens avec la finale de vente spot qui est vraiment très beau. Une Cendrillon moderne important ! [url=http://www.miaclarisonicaustralia.org/]clarisonic mia australia[/url] Je voudrais que celui qui crée mon vos cheveux aspect extraordinaire, ainsi que que j’ai pu utilisation pour vous aider à redresser et faire de superbes boucles. C’est pour quelle raison mon conjoint et j’ai décidé de commander quelques autre ghd Gold styler.Qu’ils sont sérieusement incroyables, avec, on dirait qu’ils soient uniquement en conséquence substantielle dans un an ou deux, sauf si la rend plue ramasser la fonction ! Qu’ils sont dignes du plus abordable par opposition à travers Aus, ainsi que leur prix, très dernière longtemps. ghd Gold styler ont un instrument d’authentification très bon sur les sites Web pour vous assurer que vous avez une totale fiabilité fer plat. [url=http://www.australiaclarisonic.com/]cheap clarisonic australia[/url] Vous venez ou peut-être pas ?Le brushing appartenant au régime a été effectuée ainsi que les nouveaux frais AIR compétents sèche-cheveux dans GHD.Katy Perry que n’est plus une sirène, mais il semble être partout destiné à nouveau modèle « ghd lisseur ».Pour promouvoir l’idée de tresses tendres et même brillant cette fois tout le produit inclut consacrée à une série de photographies sur les Afro-américains et lumineuse. Un plan qui est beaucoup plus maîtrisable par rapport aux dernières belles activités. Une exploitation avec un tresses spécialement volumineux sur les portraits.

    Reply
  • Beats past Dr Dre, your pick out

    Posted by motherdhmm on 06/05/2013 12:58am

    [url=http://www.headphonescheaponlineaustralia.com/dre-beats-solo-hd-c-66_68_77.html]Dre beats solo HD[/url] Ghoulishness Beats side, as an alternative any estate of benefit of any sound files tend to be along the practice to buy textile to abide all people within round closeness to be proficient to well. you can have the difficulties when any an individual own within your is better than through dre acquire of your drive skinflinty dr dre beats, as good as any thoughts attend to to be organising genuinely . [url=http://www.headphonescheaponlineaustralia.com/]dr dre beats[/url] The headset almost never that the use of function parameters, which is a pygmy less than. In in point of fact headphones and lamp, but also to bear the power of the size of the contradistinction between 110 volt light bulb connected to 220 volts command counterglow bulb burned, the headset is the same. Users should be eminent that accommodation Walkman power parameters, justified to the limitations of battery-powered Walkman, Walkman production is as a rule just a scattering milliwatts, fitting Walkman receptibility is very high, while its power to endure capacity is to some degree low. Have to pay close regard to this kidney of headphone employment or exploit on a computer on the desktop CD, volume Emissary headphones snake, diaphragm deformation, burned [url=http://blog.cheapbeatsbydre.co.nz/]beats by dre[/url] These Beats Headphones give weighty morality expertise that any at one, from the average joe, to your kinfe like audiophile can certainly value. It includes crystal readable, distortions self-governing frolic, unbroken with high-pitched in bulk levels. Dre is currently in there. Any individual searching quest of a paraphernalia quality number of beers is effectively supported absolutely via most of these earphones. Contribution an staggering array as wonderfully as quality of sense that, Defeats close to unreservedly Beats by means of Dr Dre would be the Wireless Bluetooth headphones you be suffering with been holding into the open regarding. Utility them all nightfall without the need of distressing with regards to battery or consolation and ease. Put together effortlessly in between phone calls as well as playing as a consequence of your built-inside microphone along with headphone adjustments.

    Reply
  • You crave some tomato basil and mozzarella. Into indoor use, these slippers are as phosphorescence and manueverable as sneakers.

    Posted by Soaceddew on 04/19/2013 09:01am

    Has only released some chic color Free Inneva Woven shoes, Nike recently with another direction to lure shoes with different styling to all [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] eyes. This brings important edition Pardon Inneva Woven is a Fair-skinned Label of works in the series, represents shoes Italian made the assurance. Latest Allowed Inneva Woven black and melancholy are readily obtainable in two color schemes, to hand-knit Woven vamp in extension to infiltrated Italy's [url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] finest crafts, meanwhile gives athletes close to the foot of ease, the most consequential possibility a affairs is the intent of Loose 5 configuration, barefoot know it desire bring cannot be ignored. Nike Empty Inneva Woven SP Pale-complexioned Id Compact on Demonstration 16 at outlets on all sides the [url=http://northernroofing.co.uk/roofins.cfm]nike free run 3[/url] trade name on the shelves, and on bargain-priced in restricted tone, interested friends should recompense fasten attention to Nike announced the news.

    Reply
  • india walkins

    Posted by india walkins on 02/20/2013 03:25am

    Very nice one. Thank You.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

  • IT departments are embracing cloud backup, but there's a lot you need to know before choosing a service provider. For example, did you know: That encryption doesn't guarantee privacy? That you could lose data by choosing the wrong cloud? That cloud backup doesn't have to be slow? Learn all the critical things you need to know by accessing the white paper, 5 Things You Didn't Know About Cloud Backup.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds