What you have to know about ASP. NET-----IHttpAsyncHandler Essence

Source: Internet
Author: User

First, write in front

When it comes to IHttpAsyncHandler, many people would say, ' Isn't it asynchronous IHttpHandler '?

But when I asked, "Do you really know the difference?" Are you really going to use it? This time it is estimated that a lot of people will be knocked down.

I'll analyze it as I did in the previous style, and I'll make a point of inadequacy.

Ii. Overview of the IHttpAsyncHandler

The definition given by Microsoft is simple: define the contract that the HTTP asynchronous handler object must implement .

From the source code below, it is easy to see that it inherits the interface specification of IHttpHandler. Two more methods at a time

BeginProcessRequest and EndProcessRequest methods.
 using   System;  namespace   system.web{ interface   Ihttpasynchandler:ihttphandler {IAsyncResult beginprocessrequ EST (HttpContext context, AsyncCallback cb,  object   Extradata);  void   EndProcessRequest (IAsyncResult    result); }}
using System; namespace system.web{    publicinterface  ihttphandler    {         bool  IsReusable        {            get;        }         void ProcessRequest (HttpContext context);}    }

But here's the question: how does it achieve the asynchronous effect? That is: what is the asynchronous effect? How do you achieve this asynchronous effect ?

Third, IHttpAsyncHandler in-depth understanding

1) Why can it be asynchronous?

Some people may think IHttpAsyncHandler, of course, is asynchronous. I would like to ask: wife is not a wife?

Is it really going to be asynchronous? But we know that it is not the special treatment of itself, that the user has treated him in a special way (or special treatment)

Let me boldly speculate that. Net himself did not deal with him specially

My basis is as follows (of course you can say this is httpapplication, but enough for me to infer),. NET is just judging his type, calling a different entry.

if(applicationinstance isIHttpAsyncHandler) {IHttpAsyncHandler Httpasynchandler=(IHttpAsyncHandler) applicationinstance; Httpcontext.asyncapphandler=Httpasynchandler; Httpasynchandler.beginprocessrequest (HttpContext, This. _handlercompletioncallback, HttpContext); }                Else{applicationinstance.processrequest (HttpContext);  This. Finishrequest (Httpcontext.workerrequest, HttpContext,NULL); }

So: In the end, I'm not too responsible to tell you that async itself is implemented by its own internal code. External calls just call different portals (BeginProcessRequest)

that he is not nothing great, just an interface It 's just a norm. .

2) how asynchronous?

As a multi-threaded friend, it is estimated to know how to implement multi-threaded (asynchronous), more methods. But essentially one ( with extra threads to deal with the time-consuming thing ) here, I'm simply using the ground pool to decompose ' How to implement async '---- ThreadPool.QueueUserWorkItem Method

This gives the definition of Microsoft: The method is queued for execution, and the object that contains the data used by the method is specified. This method executes when the thread pool threads become available. It's easy to say, but it doesn't seem easy to understand what to put in the queue. My understanding is as follows: There is a queue inside the online pool to hold all the things that need to be done,

The thread pool has its own bunch of dynamic threads (equivalent to porters) that they randomly go through in the queue.

A description of the method:

CallBack

Type: System.Threading . WaitCallback
A waitcallback that represents the method to execute.
State
Type: System . Object
The object that contains the data used by the method.
Return value type: System . Boolean
True if this method is queued successfully, or if the work item cannot be queued, NotSupportedException is raised .

Well, we don't have much to say. See how to implement IHttpAsyncHandler async. Look at the following example source code

Iv. examples
usingSystem;usingsystem.web;usingSystem.Threading;namespacehandler_1{classHelloworldasynchandler:ihttpasynchandler { Public BOOLisreusable {Get{return false; } }         PublicHelloWorldAsyncHandler () {} PublicIAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, Object extradata) {Contex T.response.write ("<p>begin Isthreadpoolthread is"+ Thread.CurrentThread.IsThreadPoolThread +"</p>\r\n"); Asynchoperation Asynch=NewAsynchoperation (CB, context, extradata); Asynch.            StartAsyncWork (); returnAsynch; }         Public voidendprocessrequest (IAsyncResult result) {} Public voidProcessRequest (HttpContext context) {Throw NewInvalidOperationException (); }    }    classAsynchoperation:iasyncresult {Private BOOL_completed; PrivateObject _state; PrivateAsyncCallback _callback; PrivateHttpContext _context; BOOLiasyncresult.iscompleted {Get{return_completed;} } WaitHandle IAsyncResult.AsyncWaitHandle {Get{return NULL; } } Object iasyncresult.asyncstate {Get{return_state;} }        BOOLiasyncresult.completedsynchronously {Get{return false; } }         PublicAsynchoperation (AsyncCallback callback, HttpContext context, Object State) {_callback=callback; _context=context; _state=State ; _completed=false; }         Public voidstartasyncwork () {ThreadPool.QueueUserWorkItem (NewWaitCallback (StartAsyncTask),NULL); }        Private voidStartAsyncTask (Object workitemstate) {Thread.Sleep ( the); _context. Response.Write ("<p>completion Isthreadpoolthread is"+ Thread.CurrentThread.IsThreadPoolThread +"</p>\r\n"); _context. Response.Write ("Hello World from Async handler!"); _completed=true; _callback ( This); }    }}

Note: When this asynchronous handler is called outside, it will be returned to the browser one time, not to read a lot of write.

V. Seeking attention and seeking recommendations

Brother Taiwan to encourage it, it is really a bit tired to write .... Do me a favor ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.