7.14 Use Page and Fragment Caching


Problem

You need to increase performance by caching completely rendered pages.

Solution

Add the OutputCache directive to a page or a user control, and specify how long (in seconds) the page should be kept in the cache.

Discussion

A modest use of caching can reduce bottlenecks such as database access and dramatically increase a Web site's overall performance. Caching has the greatest effect in a highly trafficked site. For example, consider what happens if you cache a page that displays the results of a database query. If you cache this page for one minute, and 10 requests are received for the page over that one- minute period, you'll reduce the database overhead by a factor of 10.

Implementing caching is easy. You simply add an OutputCache directive to the Web page. This directive must be added to the .aspx markup file, not to the .cs code-behind file. Here's an example that caches a page for 20 seconds:

 <%@ OutputCache Duration="20" VaryByParam="None" %> 

And here's an example that caches a page for 20 seconds but maintains separate cached copies depending on the value of query string arguments:

 <%@ OutputCache Duration="20" VaryByParam="*" %> 

You can test caching by using a page that displays the server date and time. You'll notice that subsequent requests for such a page won't cause it to be regenerated. Thus, the old time will be shown until the page expires .

Output caching is not effective in the following situations:

  • Your page needs to customize itself according to user-specific settings, such as user authentication information (the built-in User object) or state (the Session object). In this case, it doesn't make sense to reuse the same page for all users.

  • Your page includes controls that post back and raise server-side events.

  • Your page needs to perform another action (such as write to a log, enter some information in a database, or change an application variable). A cached page reuses the fully rendered HTML; all page code is bypassed.

  • Your page includes data that must be generated with the most current data. This might be the case for a stock lookup, but it probably won't be the case for a product catalog.

In these cases, you might still be able to use a more flexible form of caching. You can use data caching, as described in recipe 7.15, to store a specific object. Or you can use fragment caching to cache a portion of a page. To use fragment caching, create a user control that includes all the content that can be cached and add the OutputCache directive to the user control. You can then use the user control in a Web page. The Web page code will still run, but the embedded user control can be cached.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net