4.5. Cache the Data Source Control
Note: To improve the performance of your application, you should cache the data source control if you are using one.
Performing database access is a time-consuming operation; therefore, it is important that you reduce the number of times you connect to the database. The SqlDataSource control (as well as the AccessDataSource control) supports caching of data. Caching of the data source controls is useful in cases when your data does not change oftenfor example, when you have pages displaying product listings and information.
4.5.1. How do I do that?
To see how to enable caching of data source controls in your application, you will build an application in this lab that uses a SqlDataSource control to retrieve rows from the authors table in the pubs database and then uses the GridView control to display them. The SqlDataSource control will be cached for 60 seconds before the cache is invalidated.
Note: In general, the more static your data, the longer the time you should cache your data.
The default cache expiration policy is that of absolute, which means that the data cached by the data source control will expire x seconds (as specified in the CacheDuration attribute) after the data source has been loaded.
4.5.2. What about...
...sliding cache policy?
In the sliding cache policy, the cache will expire if a request is not made within a specified duration. For example, the following code specifies that the cache will have a sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be reset to another minute. Sliding expiration policy is useful whenever you have a large number of items to cache, since this policy enables you to keep only the most frequently accessed items in memory.
<asp:SqlDataSource runat="server" SelectCommand="SELECT [au_id], [au_lname], [au_fname] FROM [authors]" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>" CacheDuration="60" EnableCaching="True" CacheExpirationPolicy="Sliding" > </asp:SqlDataSource>
4.5.3. Where can I learn more?
For a good discussion on implementing page caching in ASP.NET using absolute expiration, check out the article at:
You will also learn how to cache fragments of a page in Chapter 6.