ASP. NET custom asynchronous HTTP Processing Program (Graphic tutorial)

Source: Internet
Author: User

I. Preface

1. What readers want to say:(Skip)

Here, I would like to thank those who have read the article "ASP. NET custom synchronization HTTP processing program" and read this article.ASP. NET custom asynchronous HTTP processing program. Those who have read the above articles may find many familiar points. In fact, I have introduced it in detail to give you a better understanding.

PS: from the beginning to the end of MSDN, the text is very unified. I am afraid many people are afraid and lazy to look at it. So I extracted the important part from it, use easy-to-understand examples and concise languages to describe. Of course, the errors are inevitable. I hope you can point them out.

2. Formal start

We have learned about the custom synchronous HTTP processing program. I believe you may feel some achievements (so easy ). However, this synchronization mechanism can only deal with situations where the customer has little access or the data processing capacity is not large.(Every time you apply for a synchronous HTTP processing program, a new thread will be created for processing. When the number of applications is large, the thread will be blocked, resulting in low server performance or even downtime). This article is about how to synchronize HTTP processing programs.Fatal DefectsTo effectively use server resources.

PS: asynchronous (Only in this article): In short, some operations use the threads we have created, and the other operations are processed in an orderly manner by the operating system calling its own threads, in this way, we can perform simple processing by our own threads, while complicated processing is handled by the threads managed by the system. Because these threads are managed by the system, they will not be stuck and will be automatically managed within the system. Of course, the system will notify us that the processing of the thread has been completed, so that we can avoid the use of multithreading technology, but it is difficult to manage the problem.

The following areLegend:

Ii. Registration and binding(Although the previous article has already been mentioned, I will repeat it here)

Why are there two parts? What about registration and binding?

The answer is that you can't know what you are doing by writing only one class vs, so we need to register our custom HTTP handler in web. config. Binding means that iis knows that our site contains a custom HTTP handler. (I will take iis7 as an example to describe how to bind it)

1. Registration
Copy codeThe Code is as follows:
<Configuration>
<System. web>
<HttpHandlers>
<Add verb = "*" path = "<! -- Here is the page for applying for binding the client (*. smm, *. ffs, web1.ffe) --> "type =" <! -- Write the handler class name here -->"
</HttpHandlers>
</System. web>
</Configuration>

I have used comments to write the above self-compiled parts.

2. BIND (iis7)

1) Open iis7-open website node-click the name of your website

2) double-click

3) Click

4)

5) Click OK to complete the binding in iis.(I will introduce the process in text in the complete example below)

Iii. Implementation of Classes

Here we willImplement the functions of two interfacesAnd I will separate them.Description

1. IHttpAsyncHandler Interface

The implementation method and attributes are as follows:

IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, Object extradata)
Start asynchronous calls to HTTP processing programs

Parameter description:
Context: This object provides internal server objects (suchRequest,Response,SessionAndServer.
Cb: After the asynchronous operation is complete, call this delegate to inform us that the operation has been completed.
Extradata: All additional data required to process the request
Return Value:
Return IAsyncResult about the Process status (this allows us to view the current status in asynchronous calls at any time)

Void EndProcessRequest (IAsyncResult result)
The End method of asynchronous processing is provided when the process ends.


Parameter description:
Result: IAsyncResult related to the Process status (the result here is the same object as that returned by BeginProcessRequest, but the internal attributes are changed)

Note: however, we also need to implement an attribute and a method that are not in the IHttpAsyncHandler interface. Otherwise, IIS reports an error.

Bool IsRusable
Indicates whether to use the pool. You only need to implement get. If false is returned, the pool is not used. If true is returned, the pool is used.

Void ProceessRequest (HttpContext context)
Method Called to synchronize HTTP processing programs (this method is not called here, but must be implemented)



2. iasyncresul Interface

The implementation method and attributes are as follows:

Object AsyncState
Get the User-Defined Object (in fact, the above extradata and only need to implement get)

WaitHandler AsyncWaitHandle
Obtain the WaitHandle used to wait for the completion of the asynchronous operation (usually return NULL and only need to implement get) bool CompletedSynchronously
Indicates whether asynchronous operations are synchronized (usually false). bool IsCompleted
Indicates whether the asynchronous operation has been completed.

4. implement this function(Iis7/asp.net 4.0/vs2010/windows 7 64bit)

Note: 1. Create an empty web project, add the App_Code folder, andDeploymentOn iis

2. InApp_CodeCreate a new class named "AsyncRequestHandler. cs" (the name here is not affected, but the class name is the key)

3. In AsyncRequestHandler. csReference"System. Threading" namespace

Next we will learn how to implement this function step by step. Although it is just a simple example, it can be used more flexibly in future development.

1. Implement the IHttpAsyncHandler Interface
The Code is as follows:
Copy codeThe Code is as follows:
Public class AsyncHttpHandler: IHttpAsyncHandler
{
Public AsyncHttpHandler ()
{
//
// TODO: add the constructor logic here
//
}

Public bool IsReusable
{
Get
{
Return false; // indicates that the pool is not used.
}
}

Public void ProcessRequest (HttpContext context) // do not call the required Method
{
Throw new InvalidOperationException ();
}

/// <Summary>
/// Asynchronous processing executed when the customer applies
/// </Summary>
/// <Param name = "context"> contains httpresponse, httprequest, and server objects </param>
/// <Param name = "cb"> callback function </param>
/// <Param name = "extradata"> parameters to be passed </param>
/// <Returns> returns the status information about the process. </returns>
Public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extradata) // required Method
{
Context. Response. Write ("<p> AsyncHttpHandler </p>"); // Write html to the page to indicate where the information comes from
AsyncOperation op = new AsyncOperation (context, cb, extradata); // instantiate the class that implements the IAsyncResult interface (mainly the class that implements asynchronous processing)
Op. StartAsyncWork (); // start asynchronous Processing
Return op; // return this object
}

/// <Summary>
/// When the return op in BeginProcessRequest is called after the asynchronous processing is complete (after the call, the page is displayed)
/// </Summary>
/// <Param name = "result"> It is op, but the attribute has been changed </param>
Public void EndProcessRequest (IAsyncResult result)
{
}
}

2. Implement the IAsyncResult Interface(In the same file as the above Code)
The Code is as follows:
Copy codeThe Code is as follows:
Public class AsyncOperation: IAsyncResult
{
HttpContext _ context; // Save the reference of context
AsyncCallback _ cb; // Save the reference of the callback delegate
Object _ state; // save additional information
Bool _ iscomplate; // whether to save the Asynchronous Operation

/// <Summary>
/// Constructor that passes all AsyncHttpHandler Parameters
/// </Summary>
/// <Param name = "context"> </param>
/// <Param name = "cb"> </param> // The callback cannot be overwritten. Otherwise, the client will wait permanently.
/// <Param name = "state"> </param> // This value can be used to transmit any data you need during construction.
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>
/// Obtain the current asynchronous processing status
/// </Summary>
Bool IAsyncResult. IsCompleted
{
Get
{
Return _ iscomplate;
}
}

/// <Summary>
/// Return false.
/// </Summary>
Bool IAsyncResult. CompletedSynchronously
{
Get
{
Return false;
}
}

/// <Summary>
/// Additional information will be returned
/// </Summary>
Object IAsyncResult. AsyncState
{
Get
{
Return _ state;
}
}

/// <Summary>
/// Null
/// </Summary>
WaitHandle IAsyncResult. AsyncWaitHandle
{
Get
{
Return null;
}
}

/// <Summary>
/// Indicates the main function that starts asynchronous processing (the method name can be changed, but the above call also needs to be changed together)
/// </Summary>
Public void StartAsyncWork ()
{
ThreadPool. QueueUserWorkItem (new WaitCallback (StartAsyncTask), null); // I believe many developers of. net winform
}

/// <Summary>
/// Asynchronous Operation call Method
/// </Summary>
/// <Param name = "workstate"> is the value passed by 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 has been completed.
_ Cb (this); // call the callback function to indicate completion
}
}

3. web. config Configuration

The content is as follows (the red box is the content to be added ):

4. iis binding(For details about how to bind an EIP, see section 2)

5. Test

When you write test. async or asd. async at will, the final pages displayed are consistent. In this way, our results are achieved.

5. These are just superficial

Here I want to point out that reading these does not mean that you have mastered all of them, because another part of Asynchronization is the use of shared resources. This requires the WaitHandle class, otherwise, multiple threads can access and modify the same shared resource at the same time. So the end of this article also means the beginning of a new problem, so we must 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.