Asynchronous Data Access to data source controls in ASP. NET2.0

Source: Internet
Author: User

In part 2 and Part 2, the WeatherDataSource control is created. This control runs on the xml api provided by weather.com (English) and uses WebRequest and WebResponse to access data through HTTP. So far, the service has been accessed synchronously. Therefore, page processing is blocked until the Web request is complete. This method is effective for testing pages, and may also be effective on small sites, but it will be disastrous for websites receiving large volumes of communication traffic. For example, portal pages, the weather module may be very common.

  Introduction

There are a large number of fixed threads in the thread pool that can be used for service requests. Unfortunately, this solution does not only increase the limit (it also increases the resource occupation by threads and CPU usage ). Therefore, when a page is blocked and waiting for another server, it is still occupying threads, which may lead to other incoming requests waiting for a longer time in the queue. This will lead to slow access to the site and reduce the CPU usage. In Visual Studio 2005, we introduced asynchronous pages so that controls can define the tasks they want to complete asynchronously, that is, they do not need to block the threads used to process requests. We will not describe the details of the asynchronous page itself here, which has been described previously in Dmitry (English) and Fritz Onion (English. This section describes how to use this function in the data source control and use the add-on framework to implement asynchronous data sources.

  Background

In part 2, I indirectly mentioned some odd designs of the performanceview class:

Public abstract class performanceview {
Public virtual void Select (DataSourceSelectArguments arguments,
DataSourceViewSelectCallback callback );
Protected abstract IEnumerable ExecuteSelect (
DataSourceSelectArguments arguments );
...
}

You will notice that the public Select method does not actually return any data. Instead, it accepts a callback and uses this callback to return data. It only calls the protected ExecuteSelect (which always executes synchronous data access) to retrieve the data to be returned to the data-bound control. The default implementation of the performanceview class does not actually perform any operations asynchronously. The reason is that there is no ready-made asynchronous data source control. However, the design of OM does allow asynchronous data access. In this design, data is available only after the asynchronous work is complete. Therefore, we have a callback-based model.

Those familiar with asynchronous APIs in the framework will notice the lack of asynchronous modes: Public Select, BeginSelect, and EndSelect methods. In these methods, the data binding control selects the methods to call. However, the data binding control cannot determine whether to choose synchronous API or asynchronous API. In addition, adding a property to a data binding control does not work. The data source control encapsulates detailed information about how to access data storage. Whether access to data storage occurs synchronously or asynchronously depends on whether the data source is based on semantics or custom attributes. The correct location of the potential "bool protected masyncdataaccess" attribute is suitable for the data source control. This also allows the data source control to perform data access, even if multiple data binding controls are bound to the same data source. So far, I have explained these subtle concepts contained in this architecture for many times. I hope I can clarify this design.

The last thing to note about asynchronous tasks is that whether or not the Page should execute any asynchronous tasks is entirely decided by the Page developers (through the Async attribute of the Page instruction ). Therefore, any well-written data source control must degrade to implement synchronous data access as needed.

   Framework

In this framework (the rest of the example will be used to demonstrate this point at the end of this series), The AsyncDataSource and asyncperformanceview base classes have been put together, these basic classes can be used to implement data source controls that can perform asynchronous data access. The following describes the framework content and some comments that help clarify its meaning:

Public abstract class AsyncDataSourceControl: performancecontrol,
IAsyncDataSource {
Private bool _ policmasyncdataaccess;

Protected AsyncDataSourceControl (){
_ Required masyncdataaccess = true;
}

Public virtual bool extends masyncdataaccess {
Get; set;
}

Bool IAsyncDataSource. IsAsync {
Get {return _ Your masyncdataaccess & Page. IsAsync ;}
}
}

Public abstract class asyncperformanceview: performanceview {

Protected abstract IAsyncResult BeginExecuteSelect (
DataSourceSelectArguments arguments,
AsyncCallback asyncCallback,
Object asyncState );

Protected abstract IEnumerable EndExecuteSelect (
IAsyncResult asyncResult );

Protected override IEnumerable ExecuteSelect (
DataSourceSelectArguments arguments ){
// Implement
// Abstract ExecuteSelect method,
// Use BeginExecuteSelect and EndExecuteSelect,
// Enable blocking
// Synchronize data access.
}

Private IAsyncResult OnBeginSelect (object sender,
EventArgs e, AsyncCallback asyncCallback,
Object extraData );
Private void OnEndSelect (IAsyncResult asyncResult );

Public override void Select (DataSourceSelectArguments arguments,
DataSourceViewSelectCallback callback ){
If (_ owner. IsAsync ){
// Use OnBeginSelect and OnEndSelect
// As the BeginEventHandler and EndEventHandler methods,
// Call Page. RegisterAsyncTask,
// Specify the requirements
// Perform asynchronous work. These methods will
// Call a specific
// Data source implementation by calling
//
// Abstract BeginExecuteSelect and EndExecuteSelect
// Method.
}
Else {
// Execute synchronous data access
Base. Select (arguments, callback );
}
}
...
}

   Example

Now, the new AsyncWeatherDataSource will be derived from AsyncDataSourceControl, while AsyncWeatherDataSourceView will be derived from AsyncDataSourceView.

Public class AsyncWeatherDataSource: AsyncDataSourceControl {

// Same as WeatherDataSource
}

Private sealed class asyncweatherperformanceview: asyncperformanceview {
Private AsyncWeatherDataSource _ owner;
Private WeatherService _ weatherService;

Public asyncweatherperformanceview (AsyncWeatherDataSource owner,
String viewName)
: Base (owner, viewName ){
_ Owner = owner;
}

Protected override IAsyncResult BeginExecuteSelect (cesceselectarguments arguments,
AsyncCallback asyncCallback,
Object asyncState ){
Arguments. RaiseUnsupportedCapabilitiesError (this );

String zipCode = _ owner. GetSelectedZipCode ();
If (zipCode. Length = 0 ){
Return new SynchronousAsyncSelectResult (/* selectResult */
Null,
AsyncCallback, asyncState );
}

_ WeatherService = new WeatherService (zipCode );
Return _ weatherService. BeginGetWeather (asyncCallback, asyncState );
}

Protected override IEnumerable EndExecuteSelect (IAsyncResult asyncResult ){
SynchronousAsyncSelectResult syncResult =
AsyncResult as SynchronousAsyncSelectResult;
If (syncResult! = Null ){
Return syncResult. SelectResult;
}
Else {
Weather weatherObject =
_ WeatherService. EndGetWeather (asyncResult );
_ WeatherService = null;

If (weatherObject! = Null ){
Return new Weather [] {weatherObject };
}
}

Return null;
}
}

When using this framework, you only need to implement BeginExecuteSelect and EndExecuteSelect. In their implementation process, it is usually necessary to call the BeginXXX and EndXXX methods revealed by various objects in the framework (such as WebRequest or IO stream) (IN Visual Studio 2005, you also need to call SqlDataCommand) and return IAsyncResult. In this example, there is a WeatherService helper class that encapsulates the basic WebRequest object.

For those frameworks that actually lack the asynchronous mode, you will see the valid asynchronous mode here; and The BeginExecuteSelect and EndExecuteSelect to be implemented, and you want to call the Begin and End methods to return the IAsyncResult instance.

The most interesting thing is probably the SynchronousAsyncSelectResult class (to some extent, it is a contradiction ). This class is included in the Framework. It is basically an IAsyncResult implementation that enables immediate data availability and reports true from its IAsyncResult. CompletedSynchronously attribute. So far, this is only applicable when no zip code is selected and null needs to be returned (it is meaningless to start an asynchronous task and only return null ), but as you will see below, this is also useful in other solutions.

The page infrastructure hides most of the details about performing asynchronous work in Microsoft ASP. NET context. We hope that the framework provided here will allow you to write data sources that use this infrastructure with minimal operations. However, in essence, implementing asynchronous behavior is complicated. Sometimes, I have some questions when I read this article for the first time, but I may understand it when I read it for the second time. You can use the "my comments" form below to send questions or discuss them.

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.