Principles of ASP. NET 2.0 asynchronous pages [1]

Source: Internet
Author: User

Compared with ASP. NET 1.0, ASP. NET 2.0 has great improvements. However, at the implementation level, the biggest enhancement is to provide support for asynchronous pages. Through this mechanism, well-written pages can minimize the impact of slow operations such as database and WebService calls on the website's throughput, and greatly improve the average page response speed of the website. This article will analyze the principles of this powerful mechanism in terms of usage and implementation, so that readers can better apply this mechanism.
For the lifecycle of a webpage request, the Web server receives the HTTP request from the client and transfers the request to ASP.. NET engine. The engine uses pipelines to call suitable Web applications and final pages for processing. The page performs some background operations based on the request content, such as accessing the database and calling remote WebService. The results are displayed in a visual form in the browser of the end user.
In order to increase the response speed and throughput, modern Web servers usually store Web applications and pages in a buffer pool for backup to avoid rebuilding the environment each time a request is processed. When a request arrives, the Web server obtains a temporary thread from a system thread pool and calls the processing Instance obtained from the Web application and page buffer pool to process the request, and finally return the processing result.
At first glance, this mechanism is perfect to maximize the reuse of system resources, but there is actually a lot of room for optimization.

We can further refine the process of processing a page request to the following steps:

1. The Web Server accepts the request and forwards the request by the engine.
2. Page processing requests, database access, remote WebService calls, etc.
3. The page displays the processing results in some form, such as HTML tables.
4. The Web server returns the result to the client's browser.

The first step involves the core-state network driver, which needs to be frequently switched back to the user State to forward the request to the processing engine. A large number of core and User Switching are involved. To reduce this burden, IIS 6 began to provide http. sys to directly process most requests in the core state. This is the MS In the middleware level has been done for us to optimize, we do not need to worry about.

Another potential optimization point is the objective of asynchronous pages: To enhance the concurrency of page processing requests.
After the Web server obtains a temporary thread from the thread pool, it calls the page-related code to process the request. Here, the request processing process often involves slow operations, such as database access and remote WebService calls. If the database is on the local machine, the system CPU time is only transferred from the processing thread to the background database thread. Once the processing logic is remote, for example, accessing an external independent database, or call WebService to complete an operation. At this time, this thread can only wait for the Operation to end without any need. As the thread pool for the Web server to process client requests, the maximum number of threads allowed is certainly limited. (Although this upper limit can be modified in most cases, for example, in ASP. NET, you can adjust the maximum number by modifying the processModel label of machine. config. The default value is 25 ). Once the number of requests exceeds this limit is being executed in parallel, or is waiting for a slow operation in the background, the new request will be processed because there are no available threads in the request thread pool, although the CPU load is very low, however, the error "503 server unavailable" still exists, resulting in DoS attacks on applications. Even if the upper limit is set to large, the page response speed may be reduced due to a large number of pending operations.

To handle this situation, although you can continue to increase the maximum capacity of the request processing thread pool, it is always a permanent cure. A better way is to separate request processing from page processing to prevent slow page processing from occupying the time for fast request processing. After receiving a page request from the engine, the page tries to complete the actual page processing by calling the asynchronous method. The processing result is monitored by obtaining the thread from the separate thread pool, the request processing thread that sends the page request will be released directly to continue processing other page requests. This is the basic idea of ASP. NET asynchronous pages. In fact, this idea has been put forward in ASP. NET 1.1. Fritz Onion published an article in The MSDN magazine in 2003 to discuss this issue in detail and provided a simple solution.

Aspx? Print = true "target = _ blank> Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code

The implementation provided in this article is well verified in principle. However, it is cumbersome to implement the IAsyncResult interface and custom thread pool, and the processing of HTTP context and timeout is not required.

Fortunately, ASP. NET 2.0 provides built-in support for this issue. Jeff Prosise discusses in detail the implementation ideas and usage methods in the MSDN magazine article.

Asynchronous Pages in ASP. NET 2.0

From the perspective of usage, asynchronous page support is very transparent. You only need to specify the asynchronous mode in the Page tag defined on the Page, for example:

<% @ Page Async = "true"... %>


Then, you can submit the asynchronous Page processing code through the AddOnPreRenderCompleteAsync or PageAsyncTask method of the Page type in the Page implementation code. The ASP. NET engine sets the asynchronous mode of the page to call the appropriate page processing start and end methods.

 

For most simple asynchronous processing cases, you can directly call the AddOnPreRenderCompleteAsync method to submit the processing code at the beginning and end of the page request. For example, an example of internal processing of HTTP page requests is given in the above article:
1 // AsyncPage. aspx. cs
2 using System;
3 using System. Web;
4 using System. Web. UI;
5 using System. Web. UI. WebControls;
6 using System. Net;
7 using System. IO;
8 using System. Text;
9 using System. Text. RegularExpressions;
10
11 public partial class AsyncPage: System. Web. UI. Page
12 {
13 private WebRequest _ request;
14
15 void Page_Load (object sender, EventArgs e)
16 {
17 AddOnPreRenderCompleteAsync (
18 new BeginEventHandler (BeginAsyncOperation ),
19 new EndEventHandler (EndAsyncOperation)
20 );
21}
22
23 IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
24 AsyncCallback cb, object state)
25 {
26 _ request = WebRequest. Create ("http://msdn.microsoft.com ");
27 return _ request. BeginGetResponse (cb, state );
28}
29 void EndAsyncOperation (IAsyncResult ar)
30 {
31 string text;
32 using (WebResponse response = _ request. EndGetResponse (ar ))
33 {
34 using (StreamReader reader =
35 new StreamReader (response. GetResponseStream ()))
36 {
37 text = reader. ReadToEnd ();
38}
39}
40
41 Regex regex = new Regex ("href \ s * = \ s *" ([^ "] *)" ",
42 & nb

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.