Asp. NET's custom asynchronous HTTP handler (graphics and text tutorial) _ Practical Tips

Source: Internet
Author: User
Tags httpcontext

First, the preface

1. What the reader wants to say:(can be skipped)

Here I thank those who have seen the ASP. NET's custom synchronous HTTP handler, as well as the pro of this "ASP.net custom asynchronous HTTP handler ". The previous one who might have seen MSDN will find a lot of familiar places. And I actually is a more detailed introduction, so that people better understand

Ps:msdn from beginning to end is the text and the text is very unified, I am afraid many people feel afraid, lazy to see, so I will be the important part of the extraction, using understandable examples and concise language to describe. Of course, there are also mistakes, I hope you can point out.

2. A formal start

We've learned a few things about customizing a sync HTTP handler, and I'm sure you'll feel a sense of accomplishment (Daniel may find it easy). But this kind of synchronization mechanism can only deal with less customer access or less data processing (each request for a synchronous HTTP handler will create a new thread to handle, when the application volume is very large, the thread will be blocked, resulting in poor server performance, or even downtime). And today this article is to solve this fatal flaw of the synchronous HTTP handler, the effective use of the server's resources.

PS: Asynchronous ( in the case of this article only ): In simple terms, it is a part of the operation in the use of the thread we created ourselves, the other part of the operation by the operating system calls its own thread in an orderly manner, so that we can simple processing by our own thread to complete, Complex processing is handled by a system-managed thread. Because these threads are system-managed so there is no card-death situation, the system will be automatically managed internally. Of course, the system will inform us by notification of the way our own thread has been completed, so that we can avoid the use of multithreaded technology, but difficult to manage the problem.

The following is a legend:

second, registration and binding (although the previous article has been told, but still here again)

Why do we have these two parts? And still want to register and bind these two?

The answer is that you only write a class vs it is impossible to know what you are doing, so we need to register our custom HTTP handler in Web.config. The binding is to let IIS know that our site contains a custom HTTP handler. (I'll take IIS7 as an example to illustrate how to bind)

1. Registration

Copy Code code as follows:

<configuration>
<system.web>
<add verb= "*" Path= "<!--here write the page (*.smm,*.ffs,web1.ffe)-->" type= "<!--write Handler's class name-->"
</system.web>
</configuration>

I have used the comments to write all the above parts

2. Binding (IIS7)

1 Open IIS7-"Open the Site node-" Click on the name of your site

2) Double click

3) Click

4)

5 Finally Click OK so the binding in IIS is complete (the complete example below I will describe the process in text)

Iii. on the realization of class

Here we are going to implement the functions of the two interfaces , and I'll explain them separately

1. IHttpAsyncHandler interface

The methods and properties to implement are as follows:

IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, Object Extradata)
To initiate an asynchronous call to an HTTP handler

parameter Description :
Context: This object provides references to internal server objects (such as request,Response, Session, and server) that are used to service HTTP requests.
CB: Call the delegate when the asynchronous operation is complete tells us that the operation is complete
Extradata: All additional data required to process the request
return value :
Returns IAsyncResult on the state of the process (lets us see the current state in the asynchronous call all the time)

void EndProcessRequest (IAsyncResult result)
Provides an asynchronous processing end method when the process ends


Parameter description:
Result: The IAsyncResult of the process state (result here and BeginProcessRequest return the same object, just the internal attributes, etc.)

Note: But we also want to implement a property and a method that is not in the IHttpAsyncHandler interface, or IIS will complain

BOOL Isrusable
Indicates whether to use a pool, just implement get, return false to not use, return true for use.

void Proceessrequest (HttpContext context)
Synchronize the method called by the HTTP handler (this method is not called, but it must be implemented)



2. Iasyncresutl interface

The methods and properties to implement are as follows:

Object asyncstate
Gets the user-defined object (in fact, the above extradata and just implement get)

Waithandler AsyncWaitHandle
Gets the WaitHandle that is used to wait for the completion of the asynchronous operation (generally returns null and simply implements get) bool completedsynchronously
Gets the indication that the asynchronous operation is complete synchronously (generally returns false) bool IsCompleted
Gets an indication of whether the asynchronous operation has completed

Four, realize this function (iis7/asp.net 4.0/vs2010/windows 7 64bit)

Note: 1. Create a new empty Web project and add the App_Code folder and deploy it on IIS

2. Create a new class in the App_Code named "AsyncRequestHandler.cs" (the name here does not affect, but the class name is the key)

3. referencing the "System.Threading" namespace in AsyncRequestHandler.cs

Below we will learn to realize this function step by step, although just a very simple example, but can let you in later development more flexible application.

1. Implement IHttpAsyncHandler interface
The code is as follows:

Copy Code code as follows:

public class Asynchttphandler:ihttpasynchandler
{
Public Asynchttphandler ()
{
//
TODO: Add constructor logic here
//
}

public bool IsReusable
{
Get
{
return false; Indicates that the pool is not used
}
}

public void ProcessRequest (HttpContext context)//does not invoke the method that must be implemented
{
throw new InvalidOperationException ();
}

<summary>
Asynchronous processing performed when a customer requests
</summary>
<param name= "Context" > contains HttpResponse, HttpRequest, server objects </param>
<param name= "CB" > Callback function </param>
<param name= "Extradata" > Parameters to be passed </param>
<returns> Returns status information about the process </returns>
Public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, Object Extradata)//methods that must be implemented
{
Context. Response.Write ("<p>AsyncHttpHandler</p>"); Writing HTML to a page indicates where the information comes from
AsyncOperation op = new AsyncOperation (context, CB, Extradata); Instantiate the class that implements the IAsyncResult interface (the class that mainly implements the asynchronous processing)
Op. StartAsyncWork (); Start asynchronous processing
return op; Returns the object
}

<summary>
When the return op in BeginProcessRequest is called after the asynchronous processing completes (the call ends both rendering the page)
</summary>
<param name= "Result" > op, but the property has changed </param>
public void EndProcessRequest (IAsyncResult result)
{
}
}

2. Implement IAsyncResult interface(in the same file as the above code)
The code is as follows:
Copy Code code as follows:

public class Asyncoperation:iasyncresult
{
HttpContext _context; Save a reference to the context
AsyncCallback _cb;//Save a reference to a callback delegate
Object _state;//Save additional information
BOOL _iscomplate;//whether to save the asynchronous operation is complete

<summary>
constructor to pass all the Asynchttphandler parameters in
</summary>
<param name= "Context" ></param>
<param name= "CB" ></param>//The callback cannot be overridden, otherwise the state of the client's permanent wait will appear
<param name= "state" ></param>//constructs this value can pass any data you want
Public AsyncOperation (HttpContext context, AsyncCallback cb, Object State)
{
_context = context;
_CB = CB;
_state = State;
_iscomplate = false; Indicates that the current asynchronous operation is not completed
}

<summary>
Implementation gets the state of the current asynchronous processing
</summary>
BOOL IAsyncResult.IsCompleted
{
Get
{
return _iscomplate;
}
}

<summary>
return False to
</summary>
BOOL iasyncresult.completedsynchronously
{
Get
{
return false;
}
}

<summary>
Additional information will be returned
</summary>
Object IAsyncResult.AsyncState
{
Get
{
return _state;
}
}

<summary>
is empty
</summary>
WaitHandle IAsyncResult.AsyncWaitHandle
{
Get
{
return null;
}
}

<summary>
Indicates the primary function that begins the asynchronous processing (the method name can be changed, but the above call needs to be changed together)
</summary>
public void StartAsyncWork ()
{
ThreadPool.QueueUserWorkItem (New WaitCallback (startasynctask), null); I believe a lot of playing countries. NET WinForm development must know
}

<summary>
Methods called by the asynchronous operation
</summary>
<param name= "Workstate" > The value passed for the second parameter in the QueueUserWorkItem method </param>
public void StartAsyncTask (object workstate)
{
_context. Response.Write ("<p>completion isthreadpoolthread is" + Thread.CurrentThread.IsThreadPoolThread + "</p>") ;
_iscomplate = true; Indicates that the asynchronous operation is complete
_CB (this);//Call callback function indicates completion
}
}

3.web.config Configuration

The contents are as follows (the Red box section is for what you need to add):

4.iis Bindings (how to bind see two)

5. Test

When you write at random test.async or asd.async, and so on, the final presentation of the page is consistent. That's how it works.

Five, read these are only shallow layer

Here I want to point out that reading these does not mean that you have mastered all, because there is another part of the asynchronous is the use of shared resources, this need to use the WaitHandle class, otherwise it will cause multiple threads simultaneously access and modify the same shared resources, the consequences can be imagined. So at the end of this article also means the beginning of a new problem, so we have to continue to learn.

Related Article

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.