ASP. NET asynchronous page processing-NET Programming

Source: Internet
Author: User
When ASP. NET receives a page-based request, it extracts a thread from the thread pool and distributes the request to the thread. A normal (or synchronous) page retains the thread during this request to prevent this thread from being used to process other requests. If a synchronous request becomes an I/O binding (for example, if it calls a remote web service or queries a remote database, and waits for the call to return ), the thread allocated to the request is in the suspended state before the return result is called. This affects scalability because the available threads in the thread pool are limited. If all request processing threads are blocked to wait for the I/O operation to complete, other requests are queued to wait for the thread to release. The best case is reduced throughput because requests can be processed after a long wait. The worst case is that the queue is full, and ASP. Net causes subsequent requests to fail due to the 503 "server unavailable" error.

Asynchronous pages provide excellent solutions to problems caused by I/O binding requests. Page processing starts from the thread pool thread, but when an asynchronous I/O operation starts to respond to ASP. NET signals, the thread returns to the thread pool. When this operation is completed, ASP. NET extracts another thread from the thread pool and processes the request. Because threads in the thread pool are used more efficiently, the scalability is improved. Threads pending for I/O completion can now be used to serve other requests. The direct beneficiary is a request that does not take long time for I/O operations and therefore can quickly access the pipeline. Waiting for a long time to enter the pipeline will have a negative impact on the performance of such requests.

1. The @ page command in the ASPX page introduces the async = "true" attribute.

For example:
<% @ Page Language = "C #" autoeventwireup = "true" async = "true" masterpagefile = "~ /Site. Master "codefile =" asyncpage. aspx. cs "inherits =" asyncpage "%>
<Asp: Content ID = "content1" runat = "server" contentplaceholderid = "title">
Asynchronous pages
</ASP: content>
<Asp: Content ID = "content2" contentplaceholderid = "descript" runat = "server">
This page demonstrates how to use page. addonprerendercomplete to perform asynchronous
</ASP: content>
<Asp: Content ID = "content3" contentplaceholderid = "Main" runat = "server">
<Asp: Label id = "output" runat = "server"> </ASP: Label>
</ASP: content>

2. Implement ihttpasynchandler in the background CS file. Next, you call the new page. addonprerendercompleteasync method in the early stages of the page lifetime (for example, during page_load) to register a begin method and an end method, as shown in the following code:

Protected void page_load (Object sender, eventargs E)
{
Addonprerendercompleteasync (
New begineventhandler (beginasyncoperation ),
New endeventhandler (endasyncoperation)
);
}

The following operations are interesting. This page goes through its normal life cycle until the prerender event is triggered. ASP. NET then calls the begin method registered using addonprerendercompleteasync. The task of the begin method is to start asynchronous operations such as database queries or web service calls and return immediately. At this time, the thread allocated to the request is returned to the thread pool. In addition, the begin method returns iasyncresult, which allows ASP. NET to determine the completion time of asynchronous operations. At this time, ASP. NET extracts threads from the thread pool and calls the end method. After the end is returned, ASP. NET executes the rest of the page lifecycle, including the rendering stage. Between the begin return and the end call, the request processing thread can freely serve other requests until the end is called and the delay is displayed. Because the 2.0. NET Framework provides multiple asynchronous operations, you do not even need to implement iasyncresult. Otherwise, the framework is implemented for you. The overall code of the column. The response page contains a label control with the ID "output. This page uses the system. net. httpwebrequest class to extract msdn content. Then, it analyzes the returned HTML and writes all the href target lists it finds to the label control.

Foreground aspx:

<% @ Page Language = "C #" autoeventwireup = "true" async = "true" masterpagefile = "~ /Site. Master "codefile =" asyncpage. aspx. cs "inherits =" asyncpage "%>
<Asp: Content ID = "content1" runat = "server" contentplaceholderid = "title">
Asynchronous pages
</ASP: content>
<Asp: Content ID = "content2" contentplaceholderid = "descript" runat = "server">
This page demonstrates how to use page. addonprerendercomplete to perform asynchronous
</ASP: content>
<Asp: Content ID = "content3" contentplaceholderid = "Main" runat = "server">
<Asp: Label id = "output" runat = "server"> </ASP: Label>
</ASP: content>

Backend CS

Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. net;
Using system. IO;
Using system. text;
Using system. Text. regularexpressions; // ASP. NET asynchronous callback request page processing
Public partial class asyncpage: system. Web. UI. Page
{
Private webrequest _ request; protected void page_load (Object sender, eventargs E)
{
Addonprerendercompleteasync (
New begineventhandler (beginasyncoperation ),
New endeventhandler (endasyncoperation)
);
} Public iasyncresult beginasyncoperation (Object sender, eventargs E, asynccallback CB, object state)
{
_ Request = webrequest. Create ("http://www.sina.com.cn ");
Return _ request. begingetresponse (CB, State );
} Void endasyncoperation (iasyncresult AR)
{
String text;
Using (webresponse response = _ request. endgetresponse (AR ))
{
Using (streamreader reader = new streamreader (response. getresponsestream ()))
{
TEXT = reader. readtoend ();
}
} RegEx = new RegEx ("href/S * = // s */" ([^/"] *)/" ", regexoptions. ignorecase); matchcollection matches = RegEx. matches (text); stringbuilder builder = new stringbuilder (1024); foreach (match in matches)
{
Builder. append (match. Groups [1]);
Builder. append ("<br/> ");
} Output. Text = builder. tostring ();
}
}

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.