Asp.net webform asynchronous page you should know

Source: Internet
Author: User

Programmers engaged in asp.net know that all service requests will eventually have an IhttpHandler to process, just like our most commonly used aspx page. Compared with IHttpHandler, asp.net also provides an asynchronous handler interface of the same version, which is IHttpAsyncHandler. asp.net can also implement IHttpAsyncHandler on our aspx page, not just IHttpHandler.

 

Why asynchronous page?

We all know that asp.net maintains a thread pool for processing page requests. For each new request, asp.net will retrieve an idle thread from it to instantiate the page, run the processing code, and then render the HTML, then return to the thread pool, waiting for the next time to be activated. However, if the request arrives too frequently and the response time is shorter than the response time of our thread processing page, the request will be put into a queue. If the queue is full, A 503 service cannot be used to reject other requests.

As you can imagine, if our page is waiting for a slow server to process a large amount of data, read remote files, or return data from a WEB service, then there is no code to execute on the page, however, this thread will be suspended, which will seriously consume available threads and affect website concurrency.

Through asynchronous pages, we can migrate these time-consuming processes to other thread pools. When these asynchronous tasks are completed, asp.net will receive a notification to activate an available thread from the thread pool again, process the remaining work and finally render HTML.

 

Create an asynchronous page

Creating an asynchronous page is much simpler than we think,First, add an Async feature in the Page command and set it to true.

    <%@ Page Async="true" AsyncTimeout="60" ...

Another timeout feature is used to specify the asynchronous timeout time. The unit is s and the default value is 45 s.

 

Next, we need to call AddOnPreRenderCompleteAsync to register asynchronous processing:

    protected void Page_Load(object sender, EventArgs e)    {        AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginHandler), new EndEventHandler(EndHandler));    }

 

AddOnPreRenderCompleteAsync also provides another overloaded version

public void AddOnPreRenderCompleteAsync(BeginEventHandler beginHandler,EndEventHandler endHandler,Object state)

First, it is essential to start the delegation of an asynchronous task and process the callback at the end of the asynchronous process. Another parameter allows us to pass some state information to the Asynchronous Start method.

 

Asynchronous page execution

Before we show BeginHandler and EndHandler, let's repost them from an image of MSDN below to see how asynchronous processing works:

 

We can see that the registered BeginHandler starts execution after prePrend. At this time, the thread has returned to the thread pool, and the code processing has been handed over to BeginHandler,We must start asynchronous processing here.After processing, the IAsyncResult result is returned, and then the EndHandler is called. Then, another thread in the thread pool is activated and the page process is processed.

 

Effective asynchronous Processing

At this point, you may feel that asynchronous pages are clearly a pitfall. In the end, we still need to Implement Asynchronous processing for a time-consuming operation.

However, this may not be much for us. We have many ways to start asynchronous processing, ThreadPool. the QueueUserWorkItem class creates a dedicated Thread, the ininvoke of the delegate, and the built-in asynchronous support in the class library, such as the BeginExecuteReader of Command, but we can select less than that.

 

The first type is the entrusted BeginInvoke and ThreadPool. queueUserWorkItem, which will be activated from the asp.net request thread pool for processing. This is the same as releasing a thread and getting a thread from the thread pool. Isn't it a fart? The website's concurrent processing capability cannot be enhanced at all, and the waste of thread scheduling is also unnecessary.

 

Second, the Thread class creates a dedicated Thread. This can achieve the goal and the server can not handle the work, but this is very dangerous. If such requests are too frequent and too many threads are created, this puts pressure on the server and may cause the server to no longer be able to process other requests. Of course, you can implement a custom thread pool to manage these threads, so that they can be kept in a suitable range and there are always available threads available, however, this development cost is too high.

 

Next, only. net built-in BeginExecuteReader, IO inread and BeginWriter of Data Command are supported to process Asynchronization. In fact, this is also the most appropriate Asynchronous Method. The issue of letting. net manage threads does not take threads from the current request thread pool. It is also simple and powerful to use.

 

Asynchronous implementation

Then, we paste the BeginHandler and EndHandler codes as an example:

Private SqlConnection con; private SqlCommand cmd; private IAsyncResult BeginHandler (Object obj, EventArgs args, AsyncCallback cb, Object state) {string conStr = ""; con = new SqlConnection (conStr ); cmd = new SqlCommand ("select * from... ", con); con. open (); return cmd. beginExecuteReader (cb, state);} private void EndHandler (IAsyncResult ar) {try {SqlDataReader reader = cmd. endExecuteReader (ar ); ............... } Catch (Exception ex) {// error handling }}

 

In this way, a simple asynchronous page model is implemented. For these time-consuming operations, we may use cache, so that we can customize a class that implements IAsyncResult, include the data we want to use and judge whether the cache exists in BeginHandler. If a custom instance is returned and the instance is filled with the cache, asynchronous operations will be performed if it does not exist; in EndHandler, return instances are distinguished, and data is used to update the cache.

 

Multiple asynchronous tasks

If you want to process multiple Web Services, wait for the web service at the same time, and perform database operations, what should we do?

 

1. We can call AddOnPreRenderCompleteAsync multiple times to input the corresponding in and end delegate each time, but the registered tasks are executed sequentially, that is, the second task will be executed only after the first task end is processed.

 

2. We only call AddOnPreRenderCompleteAsync once, and how many asynchronous operations are started in begin, but this operation has too many limitations and will be more complicated.

 

3. Not surprisingly, asp.net provides such a solution. The method is as follows:

            PageAsyncTask taska = new PageAsyncTask(                new BeginEventHandler(BeginHandler1),                 new EndEventHandler(EndHandler1),                 null,                 null                );            Page.RegisterAsyncTask(taska);            PageAsyncTask taskb = new PageAsyncTask(                new BeginEventHandler(BeginHandler2),                new EndEventHandler(EndHandler2),                null,                null                );            Page.RegisterAsyncTask(taskb);

In this way, the registered asynchronous task will be executed at the same time. When all the asynchronous tasks are completed, the process for the remaining pages will start.

 

Finally, let's take a look at the reload version of PageAsyncTask:

public PageAsyncTask (BeginEventHandler beginHandler,EndEventHandler endHandler,EndEventHandler timeoutHandler,Object state,bool executeInParallel)

Besides the operation parameters of the first two tasks, it also provides a processing program for timeout, an object that indicates the task state, and a Boolean value that indicates whether to execute tasks with other tasks at the same time.

 

Last

There is no best, only the most suitable, and none of the processing methods will be perfect, as master Jeffrey said in asynchronous operations: we should try to limit the use of threads as much as possible. Although asynchronous pages allow our website to process more requests, they do not make your users feel that page rendering is faster or even slower, because the creation thread itself will produce a certain amount of consumption, and the switching overhead between threads is also quite large. Remember.

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.