Asynchronous Web parts

Source: Internet
Author: User
Released on: 2006-07-31 | Updated on: 2006-07-31

Fritz onion

DownloadCode: Onion2006_07.exe (176kb)

Content on this page
Web component congestion
Asynchronous Web Access
Working Principle
Asynchronous Data Access

With the portal infrastructure of ASP. NET 2.0, you can easily build custom websites, including Web parts sets that can be inserted. This model is highly flexible and allows users to easily place Web parts anywhere on a webpage, so they can freely customize websites. However, these advantages will also lead to inefficient user experience, because you cannot predict which components will be used at the same time, and thus cannot provide specific data retrieval Optimization for each individual component.

The most common inefficiency of a typical portal website occurs when multiple Web Components send network data requests at the same time. Each request, whether it is a request to the Web service or remote database, will eventually increase the total time required to process the page, even if these requests are independent from each other and ensure that they are sent in parallel.

Fortunately, Asp. NET 2.0 also introduces an easy-to-use Asynchronous page model, which is used in combination with asynchronous web service calls and asynchronous database access, it can significantly improve the portal page response speed when multiple independent Web parts collect data in parallel. In this article, we will focus on building Web Components that execute asynchronous data retrieval to enable portal pages containing these components to have higher response speed and scalability technologies.

Web component congestion

First, let's take a look at the portal page shown in 1. In this example, the portal page contains four Web Components that retrieve data from different sources. The sample application is complete.Source codeYou can download the application from the msdnmagazine website. We recommend that you view the application after reading this column. In this example, three Web parts use the Web service to retrieve data and intentionally wait three seconds before returning the data. The fourth Web part sends an ADO. Net query to the SQL Server database, and waits for three seconds before returning. This example is exaggerated, but it is not impossible.

Figure 1 portal page example

Each Web Part in the example application is built by the user control and the data retrieval result is bound to the control that displays it. The code and tag quantity of each control are kept to a minimum, so this example is simple and easy to understand, allowing you to focus more on how to make Web parts asynchronous.

The following is the newswebpart. ascx user control file:

<% @ Control Language = "C #" autoeventwireup = "true" codefile = "newswebpart. ascx. CS "inherits =" webparts_newswebpart "%> <asp: bulletedlist id =" _ newsheadlines "runat =" server "> </ASP: bulletedlist>

The source code for the Web part of the news title example is as follows:

 
Public partial class webparts_newswebpart: usercontrol {protected void page_load (Object sender, eventargs e) {portalservices PS = new portalservices (); _ newsheadlines. datasource = ps. getnewsheadlines (); _ newsheadlines. databind ();}}

Note that it interacts with the Web service to retrieve the example news title. The execution process of the stock quote Web component is basically the same as that of the weather forecast Web component, except that different methods of the same web service are used to retrieve the required data. Similarly, Figure 2 shows the salesreportwebpart. ascx user control file of the Web part of the sales report sample and its contained code page. Note how to use ADO. Net to retrieve sales data from the database and use the data to fill the gridview control.

Figure 3 Web Part sequence processing

Once the sample portal page starts running, the problem is displayed. If the request processing time exceeds 12 seconds, this delay will make most users reluctant to use the application. The reason for this long delay is 3, which tracks the request execution path when the page is executed. Like other controls in the page control hierarchy, each Web part is loaded in sequence according to the page control hierarchy definition. Since this process is performed in order, each Web Part must wait for the component in the hierarchy to complete before it starts its data request and prepares a response. With the 3-second delay of human in each data retrieval, you can understand why it takes 12 seconds to complete the response. Each Web component performs completely independent data retrieval. The most important thing to note here is that these retrieval operations can be executed in parallel, thus saving 75% of the response time. This is what I want to achieve.

Back to Top

Asynchronous Web Access

In this example, three web components use web services to retrieve data, and one component uses ADO. Net to access the database. Let's start with asynchronous web service calling, because the Web Service Description Language tool wsdl.exe (or Visual Studio 2005 add web service reference tool) the generated Web Service proxy class provides good support for executing asynchronous web method calls.

When you create a Web Service proxy class in ASP. NET 2.0, three different methods are generated to call any specific method: synchronous and asynchronous. For example, the Web Service proxy used by Web components can call the getnewsheadlines web method using the following methods:

Public String [] getnewsheadlines () Public iasyncresult callback (asynccallback callback, object asyncstate) Public String [] endgetnewsheadlines (iasyncresult asyncresult) Public void publish (Object userstate) public eventgetnewsheadlinescompletedeventhandlergetnewsheadlinescompleted;

The first method getnewsheadlines is the standard synchronization method. The last two methods, begingetnewsheadlines and endgetnewsheadlines, can be used to call Methods asynchronously and can be nested into any number of. Net asynchronous mechanisms through the standard iasyncresult interface.

The most noteworthy method in this solution is getnewsheadlinesasync. To use this specific method, you must register the proxy event Delegate, which is specially generated to capture asynchronous call results (for example, the getnewsheadlinescompleted event in the example ). The delegate signature is a strong type that contains a method return value. Therefore, the result can be easily extracted from the method implementation.

With this event-based Asynchronous Method, you can easily override the asynchronous web method call in the title news Web component, as shown in figure 4. First, subscribe to the delegate of the proxy class getnewsheadlinescompleted event, and then call the getnewsheadlinesasync method. When the event method is subscribed to, the web method call result is bound to bulletedlist and displayed to the customer. Note that these asynchronous methods work only when you place a Web part on a page with the async = "true" attribute setting. You can check the isasync attribute on the page programmatically. If the page where the Web part is placed is not asynchronous, You need to resort to standard synchronous binding, as shown in figure 4.

Now, to ensure that asynchronous Web parts can perform asynchronous data retrieval, they must be placed on the page where the async attribute is set to true. Therefore, modify the page command of the portal page as follows:

 
<% @ Page Language = "C #" autoeventwireup = "true" async = "true" %>

After the other two Web Components that use Web Services for asynchronous data retrieval are updated, the portal page responds faster. In fact, according to the loading sequence of different parts, the customer can get the response result in about 3 seconds (if it takes about 6 seconds to load and sell Web parts first )! Even if the sales report web parts still access the database sequentially, the other three Web parts will execute their Web Service asynchronous calls at the same time, so the main request thread will not wait too long. Of course, the ultimate goal is to make all the I/O bindings work asynchronously, so that customers can use web services and database-driven Web components at the same time, this avoids unnecessary sequential blocking.

Another reason for pushing I/O binding to asynchronously process I/O requests is to release the main thread back to the thread pool to process other requests. My current practice is to release the thread only after the query of the Sales Report database is completed. That is to say, it takes three seconds to occupy the thread pool thread that could originally process other requests. If the last Data Binding Request is set to asynchronous, the time when the page uses the request thread is only the time when all asynchronous I/O requests are released, then return to the thread pool immediately.

Back to Top

Working Principle

If you have been engaged in asynchronous programming, you may feel that local changes to Web service calls are far from enough. I have not involved the iasyncresult interface yet, and I do not need to let the inclusion page know that an asynchronous operation is being performed (by registering a task or other technology), but everything can work as I want.

The secret lies in the implementation of the asynchronous Web Service proxy class and the help of asyncoperationmanager introduced in Microsoft. NET Framework 2.0.ProgramClass. Every time you call the proxy class getnewsheadlinesasync method, It maps the call to the internal helper method of the soaphttpclientprotocol base class, called invokeasync, and the proxy class is derived from this. Invokeasync has two important functions: Registering asynchronous operations by calling the asyncoperationmanager static createoperation method and starting asynchronous requests by using the begingetrequeststream method of the webrequest class. At this time, the call is returned, and the page continues to process its lifecycle. However, since the page has been marked as async = "true", it continues to process requests until the prerender event, then return the request thread to the thread pool. After the asynchronous Web request is complete, the method of subscribing to the agent completed event is called through a separate thread in the I/O thread pool. If this is the final Asynchronous Operation (Tracking Based on the asyncoperationmanager synchronization Environment), the page will be called back, in addition, the request continues the processing from the interrupted location (starting from the prerendercomplete event ). Figure 5 shows the full lifecycle of asynchronous Web requests on an asynchronous page.

Figure 5 asynchronous Web requests on an asynchronous page

Asyncoperationmanager is a class specifically designed to help Asynchronous Method call management in different environments. For example, if a Web Service is asynchronously called from a Windows Forms Application, the asyncoperationmanager class is connected at the same time. The difference between each environment is the synchronizationcontext associated with asyncoperationmanager. When running in an ASP. NET-based application environment, synchronizationcontext is set to an instance of the aspnetsynchronizationcontext class. The main purpose is to track the number of asynchronous requests waiting for processing, so that after these requests are processed, they can continue page request processing. In contrast, when running in a Windows Forms-based application environment, synchronizationcontext is set to an instance of the windowsformssynchronizationcontext class. The main purpose is to make calling and sending between background threads and UI threads easier.

Back to Top

Asynchronous Data Access

Now let's go back to the final asynchronous question about Web components and the frequently asked questions about asynchronous data retrieval using ADO. net. Unfortunately, there is no simple asynchronous mechanism similar to the Web Service proxy to perform asynchronous data retrieval, so you have to do some additional work to make the final Web Part truly asynchronous. I can use the new Asynchronous Method of the sqlcommand class together with the asynchronous task function of ASP. NET. Through sqlcommand, you can use one of the following methods to call commands asynchronously:

Iasyncresult beginexecutereader (asynccallback AC, object state)

Iasyncresult beginexecutenonquery (asynccallback AC, object state)

Iasyncresult beginexecutexmlreader (asynccallback AC, object state)

After the data stream is ready to be read, you can call the corresponding completion method:

Sqldatareader endexecutereader (iasyncresult AR)

Int endexecutenonquery (iasyncresult AR)

Xmlreader endexecutexmlreader (iasyncresult AR)

To use these asynchronous retrieval methods, you must add "async = true" to the connection string ". In this case, I want to bind the gridview to sqldatareader and then fill it in. Therefore, the beginexecutereader method is used to start asynchronous calls.

To connect this to an asynchronous page, ASP. NET 2.0 allows you to register an asynchronous task that needs to be executed before the page is displayed. Compared with the model used in Web Service proxy, this is a more explicit model, but it also has greater flexibility. To register an asynchronous task, I created an instance of the pageasynctask class and initialized it using three delegates: Start, end, And timeout. The START handler must return an iasyncresult interface to start asynchronous data requests using beginexecutereader. After the task is completed, call the End Processing Program (when preparing to read data in this example). You can use these results. ASP. NET calls the start handler before it starts to release the request thread (followed by the completion of the prerender event ). Figure 6 shows the update Implementation of the Web component of the sales report. It uses asynchronous tasks and the asynchronous beginexecutereader method of the sqlcommand class to execute asynchronous data access.

Note that this same technology can be used in Web Service requests by using other asynchronous methods provided by the proxy class (such as begingetnewsheadlines. Another potential advantage of this technology is that you can specify a timeout handler. If remote calls cannot be returned in time, the associated timeout handler will be called. Use the asynctimeout attribute in the page command to specify the timeout value. The default value is 20 seconds. Note that, unlike the event-based asynchronous mode, when you use page. registerasynctask, you do not need to create a branch for asynchronous calls based on page. isasync results. Asynchronous page tasks of Web parts can run normally on Asynchronous pages, and even support parallel execution of Web parts. The core difference is that when an asynchronous page (without the async = "true" attribute) is executed, the home page thread will not be released back to the thread pool.

Now that all Web Components perform data retrieval asynchronously, you can use these components in all pages marked as Asynchronous, and we know that, the current response time is no longer the sum of the time used by all Web parts to retrieve their data, but the longest time needed for any Web part. By marking pages as asynchronous and using Web Components that execute asynchronous I/O, the potential scalability of websites can be improved. This is because the main request thread can be released to serve other customers while waiting for data. The key here is whether you use ASP. NET 2.0 to create a portal. You need to pay attention to all the new asynchronous functions introduced in this version, and make full use of them to improve application responsiveness and scalability. For more information about asynchronous support in ASP. NET 2.0, seeArticle.

Please send your questions and comments to Fritz via xtrmasp@microsoft.com.

Fritz onion is one of the co-founders of pluralsight (a Microsoft. NET training provider) and hosts the web development project. Fritz is the author of essential ASP. NET (Addison Wesley, 2003) and the forthcoming essential ASP. NET 2.0 (Addison Wesley, 2006 ). To learn more about this author, log on to pluralsight.com/fritz.

This article is taken from msdn magazine, published in June 2006.

2006 Microsoft Corporation is copyrighted. All rights reserved. Usage rules.

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.