Unleash the power of async in ASP.

Source: Internet
Author: User

Brij Bhushan Mishra

Asynchronous programming has received great attention in recent years, mainly for two key reasons: first, it helps to provide a better user experience because it does not block the UI thread and avoids the UI hangs before processing ends. Second, it helps to scale the system significantly, without adding additional hardware.

However, writing the appropriate async code to manage the thread itself is a tedious task. Nonetheless, its huge benefits have allowed many new and old technologies to start using asynchronous programming. Microsoft has invested a lot in it since releasing. NET 4.0, and then introduced the async and await keywords in. NET 4.5, making asynchronous programming easier than ever.

However, the asynchronous features in ASP. NET can be used from the start, but never get the attention they deserve. Also, given the way that ASP. NET and IIS handle requests, the benefits of asynchrony may be more pronounced. With Asynchrony, it's easy to dramatically increase the extensibility of your ASP. As new programming constructs are introduced, such as async and await keywords, we should also learn to use the power of asynchronous programming.

In this blog post, we will discuss how IIS and ASP. NET processing requests, and then see where in ASP. NET can use Asynchrony, and finally discuss several scenarios that best reflect the benefits of asynchrony.

How is the request handled?

Each ASP. NET request is first passed through IIS and then finally processed by the ASP. First, IIS receives the request, sends it to ASP. NET (must be an ASP), then actually processes it and generates a response, which is then sent back to the customer via IIS. On IIS, some worker processes are responsible for fetching requests from the queue, executing the IIS module, and then sending the request to the ASP. However, ASP. NET itself does not create any threads, nor does it process the request's thread pool, but instead uses the CLR thread pool to get the thread to process the request. Therefore, the IIS module calls ThreadPool.QueueUserWorkItem and queues the request for processing by the CLR worker thread. As we all know, the CLR thread pool is managed by the CLR and can be automatically adjusted (that is, it creates and destroys processes as needed). It is also important to remember that creating and destroying threads is a heavy task, which is why the CLR thread pool allows multiple tasks to be handled using the same thread. Let's look at a diagram that describes the process of request processing.

650) this.width=650; "src=" Http://news.oneapm.com/content/images/2016/04/8765-Brij_pic_1.png "title=" "style=" height:auto;vertical-align:middle;border:0px; "/>

As can be seen in, the request is first received by HTTP. Sys and added to the appropriate kernel-level application pool queue. An IIS worker thread then pulls the request out of the queue and processes it to the ASP. Note that if the request is not an ASP. NET request, it will be returned automatically from IIS. Finally, a thread is allocated from the CLR thread pool that handles the request.

Asp. What are the asynchronous usage scenarios in net?

All requests can be broadly divided into two categories:
1. CPU Bound class
2. I/O Bound class

CPU Bound class requests, which require CPU time and are executed in the same process, while the I/O Bound class request is inherently blocking and relies on other modules to perform I/O operations and return a response. Blocking requests are a major impediment to increasing application scalability, and most Web applications waste a lot of time waiting for I/O operations. Therefore, the following scenarios are suitable for asynchronous use:

    1. I/O Bound class requests, including:

      A. Database access

      B. read/write files

      C. WEB Service invocation

      D. Access to network resources

    2. Event-driven requests, such as SIGNALR

    3. Scenarios where data needs to be fetched from multiple data sources

As an example, here you create a simple synchronization page and then convert it to an async page. This example sets a delay of 1000ms (to simulate some heavy database or Web service calls, etc.), and also uses WebClient to download a page as follows:

protected void Page_Load (object sender, EventArgs e) {System.Threading.Thread.Sleep (1000);        WebClient client = new WebClient (); String downloadedcontent = client.        Downloadstring ("https://msdn.microsoft.com/en-us/library/hh873175%28v=vs.110%29.aspx"); Dvcontainer.    InnerHtml = downloadedcontent; }

Now the page is converted to an asynchronous page, which involves three steps mainly:

    1. In the page directive, add async = True to convert the page to an asynchronous page, as follows:

<%@ page language= "C #" autoeventwireup= "true" codebehind= "Home.aspx.cs" inherits= "Asynctest.home" async= "true" asynctimeout= "%>"

AsyncTimeout (optional) is also added here, please select according to your needs.

2. Convert this method into an async method. Put Thread.Sleep and client here. The downloadstring is converted to an async method as follows:

Private async Task Asyncwork () {await task.delay (1000);        WebClient client = new WebClient (); String downloadedcontent = await client.        Downloadstringtaskasync ("https://msdn.microsoft.com/en-us/library/hh873175%28v=vs.110%29.aspx"); Dvcontainer.    InnerHtml = downloadedcontent; }

3. This method can now be raised directly on Page_Load (page load) to make it asynchronous, as follows:

protected async void Page_Load (object sender, EventArgs e) {await asyncwork (); }

But the type of Page_Load returned here is async void, which should be avoided in any case. We know that Page_Load is part of the entire page life cycle, and if we set it to asynchronous, there may be some anomalies and events, such as the life cycle has finished and the page load is still running. Therefore, it is strongly recommended that you use the RegisterAsyncTask method to register asynchronous tasks that are executed at the appropriate time in the life cycle to avoid any problems.

protected void Page_Load (object sender, EventArgs e) {registerasynctask (new PageAsyncTask (asyncwork)); }

Now that the page has been converted into an asynchronous page, it is no longer a blocking request.

The author has deployed synchronous pages and asynchronous pages on IIS8.5, and tested both with burst load. The test results found that the same machine configuration, the synchronization page can only fetch 1000 requests in 2-3 seconds, and the asynchronous page can provide services for more than 2,200 requests. Thereafter, you start to receive a timeout (timeout) or an error that the server is not available (server not Available). Although the average request processing time for both is not very different, the asynchronous page can handle more than twice times the request. This is enough to prove that asynchronous programming is powerful, so you should take advantage of it.

Asp. There are several places in net that can also introduce asynchrony:

    1. Writing asynchronous modules

    2. Writing asynchronous HTTP Handlers using IHttpAsyncHandler or Httptaskasynchandler

    3. Using the Web Sockets or SignalR

Conclusion

In this blog post, we discuss asynchronous programming and find that the new async and await keywords make asynchronous programming very simple. The topics we discuss include how IIS and ASP are handling requests, and in which scenarios the role of asynchrony is most pronounced. In addition, we have created a simple example that discusses the benefits of asynchronous pages. Finally, we have added several places where you can use async in ASP.

This article is compiled and presented by OneAPM engineers. OneAPM can help you easily lock down. NET application performance bottlenecks, with powerful Trace records to layer through analysis until the line-level problem code is locked. Displays the system response speed at the user's point of view, and counts user usage in geographic and browser dimensions. To read more technical articles, please visit the ONEAPM official blog.

Original address: http://www.infragistics.com/community/blogs/brijmishra/archive/2015/10/28/ Leveraging-the-power-of-asynchrony-in-asp-net.aspx

This article was transferred from OneAPM official blog


Unleash the power of async in ASP.

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.