Microsoft ASP.NET: An Overview of Caching Holly Mazerolle Developer Support Engineer Microsoft...
-
Author
caroline-fox -
Category
Documents
-
view
219 -
download
1
Embed Size (px)
Transcript of Microsoft ASP.NET: An Overview of Caching Holly Mazerolle Developer Support Engineer Microsoft...

Microsoft ASP.NET: An Microsoft ASP.NET: An Overview of CachingOverview of Caching
Holly MazerolleHolly MazerolleDeveloper Support Engineer Developer Support Engineer Microsoft Developer Support Microsoft Developer Support Microsoft CorporationMicrosoft Corporation

2
OverviewOverview
Introduction to ASP.NET cachingIntroduction to ASP.NET caching Output cachingOutput caching Fragment cachingFragment caching Data cachingData caching

3
Introduction to Caching in Introduction to Caching in ASP.NETASP.NET
Caching is the most critical factor in creating Caching is the most critical factor in creating scalable, high performance Web applicationsscalable, high performance Web applications
Caching locationsCaching locations Web server, proxy server, and client browsersWeb server, proxy server, and client browsers
Types of cachingTypes of caching Output cachingOutput caching Fragment cachingFragment caching Data cachingData caching

4
Output CachingOutput Caching
What is output caching?What is output caching? @ OutputCache directive and the cache @ OutputCache directive and the cache
objectobject Output caching attributes: Output caching attributes:
DurationDuration LocationLocation VaryByParamVaryByParam VaryByHeaderVaryByHeader VaryByCustomVaryByCustom

5
What Is Output Caching?What Is Output Caching?
Pages that use the output cache are executed Pages that use the output cache are executed one time, and the page results are cachedone time, and the page results are cached
The pre-executed page is then served to later The pre-executed page is then served to later requestsrequests
Performance and scalability both benefitPerformance and scalability both benefit Server response times reducedServer response times reduced CPU load reducedCPU load reduced
Appropriate caching of pages affects site Appropriate caching of pages affects site performance dramatically performance dramatically

6
@ OutputCache Directive and the @ OutputCache Directive and the Cache ObjectCache Object
@ OutputCache declaratively controls @ OutputCache declaratively controls caching behaviorcaching behavior For .aspx, .asmx, or .ascx For .aspx, .asmx, or .ascx
The cache object programmatically controls The cache object programmatically controls caching behaviorcaching behavior
<%@ OutputCache Duration="600“ Location="Any“VaryByParm=“none” %>
Is equivalent to:[C#]Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));Response.Cache.SetCacheability(HttpCacheability.Public);

7
OutputCache Members: OutputCache Members: Duration and LocationDuration and Location
Duration sets the time to cache the outputDuration sets the time to cache the output In secondsIn seconds RequiredRequired
Location sets the location to cache the outputLocation sets the location to cache the output ServerServer: The output is held in memory on the Web server : The output is held in memory on the Web server
and is used to satisfy requestsand is used to satisfy requests DownstreamDownstream: A header is added to the response to : A header is added to the response to
indicate to proxy servers to cache the pageindicate to proxy servers to cache the page ClientClient: A header is added to the response indicating to : A header is added to the response indicating to
browsers to cache the pagebrowsers to cache the page AnyAny: Output cache can be located on any of these : Output cache can be located on any of these
locationslocations NoneNone: No output caching is turned on for the item: No output caching is turned on for the item
<%@ OutputCache Duration="600" Location="Any“VaryByParam=“none” %>

8
OutputCache Members: OutputCache Members: VaryByParam and VaryByHeaderVaryByParam and VaryByHeader
VaryByParamVaryByParam The cache stores multiple copies of a page based on The cache stores multiple copies of a page based on
specific Querystring or Form parameters and any specific Querystring or Form parameters and any combinations thereofcombinations thereof
VaryByHeaderVaryByHeader The cache stores multiple copies of a page based on The cache stores multiple copies of a page based on
HTTP headersHTTP headers
<%@ OutputCache Duration="10“ VaryByParam="location;count" %>
<%@ OutputCache Duration="60“ VaryByHeader="Accept-Language" %>

9
OutputCache Members: OutputCache Members: VaryByCustomVaryByCustom
VaryByCustomVaryByCustom If the value is “Browser,” cache varies by browser type and If the value is “Browser,” cache varies by browser type and
major versionmajor version If the value is a custom string, you must override If the value is a custom string, you must override
HttpApplication.GetVaryByCustomString in the Global.asax HttpApplication.GetVaryByCustomString in the Global.asax and implement your own caching logicand implement your own caching logic

10
Fragment CachingFragment Caching
What is fragment caching?What is fragment caching? VaryByControlVaryByControl Nested cached user controlsNested cached user controls Cached controls are not programmableCached controls are not programmable

11
What Is Fragment Caching?What Is Fragment Caching?
Just as you can vary the versions of a page Just as you can vary the versions of a page that are output cached, you can output cache that are output cached, you can output cache regions of a pageregions of a page
Regions are defined based on user controlsRegions are defined based on user controls User controls contain their own User controls contain their own
@OutputCache [email protected] directive Fragment caching supportsFragment caching supports
VaryByParamVaryByParam VaryByControlVaryByControl
Location not supported because fragments Location not supported because fragments must reside on server to be assembledmust reside on server to be assembled

12
Fragment Caching a User ControlFragment Caching a User Control[*.ascx][*.ascx]
<%@ Language="C#" %> <%@ Language="C#" %>
<%@ OutputCache Duration="10“ <%@ OutputCache Duration="10“ VaryByControl="State;Country" VaryByControl="State;Country"
VaryByParam="*"%> VaryByParam="*"%>
<script runat=server> <script runat=server>
public String State { public String State {
get { return state.Value; } get { return state.Value; }
set { state.Value = State; } } set { state.Value = State; } }
public String Country { public String Country {
get { return country.Value; } get { return country.Value; }
set { country.Value = Country; } } set { country.Value = Country; } }
</script></script>

13
VaryByControlVaryByControl
VaryByControlVaryByControl The sixth attribute supported by OutputCacheThe sixth attribute supported by OutputCache Only supported in user control cachingOnly supported in user control caching Caching is based on user control propertiesCaching is based on user control properties
<%@ OutputCache Duration="10“ VaryByControl="State;Country“ VaryByParam="*"%>

14
Nested Cached User Controls Nested Cached User Controls
User controls can be nestedUser controls can be nested Cached user controls can also be nestedCached user controls can also be nested Since multiple versions of a user control are Since multiple versions of a user control are
cached, this creates a hierarchy of cached cached, this creates a hierarchy of cached outputoutput
This caching treeThis caching tree Is very efficient and powerfulIs very efficient and powerful Requires almost nothing from a developerRequires almost nothing from a developer
Varying by many properties could create a Varying by many properties could create a large tree, and therefore, a large memory large tree, and therefore, a large memory footprintfootprint

15
Cached Controls Are Not Cached Controls Are Not Programmable Programmable Do not try to programmatically access a user Do not try to programmatically access a user
control that is in the cachecontrol that is in the cache Cached controls are not added to the control Cached controls are not added to the control
treetree Trying to access a cached control will throw Trying to access a cached control will throw
an exceptionan exception

16
Data CachingData Caching
What is data caching?What is data caching? Working with the cache objectWorking with the cache object Cache dependenciesCache dependencies Scavenging memoryScavenging memory Using callbacks with cachingUsing callbacks with caching

17
What Is Data Caching?What Is Data Caching?
The data cache holds application data such The data cache holds application data such as strings, datasets, and other objectsas strings, datasets, and other objects
Adding items to the data cache is easyAdding items to the data cache is easy
Although similar to the familiar application Although similar to the familiar application variables model, it is much more powerfulvariables model, it is much more powerful
Cache (“counter”) = mycount.text
Application(“counter”) = mycount.text

18
Working with the Cache ObjectWorking with the Cache Object Cache object featuresCache object features
Dependencies allow logic to invalidate cached Dependencies allow logic to invalidate cached itemsitems
Scavenging (automatic expiration)Scavenging (automatic expiration) Callbacks when an item is removed from cacheCallbacks when an item is removed from cache
To use dependencies or callbacks, use To use dependencies or callbacks, use Cache.Insert or Cache.AddCache.Insert or Cache.Add
Code using cached items must be able to Code using cached items must be able to both create or insert, and retrieve cached both create or insert, and retrieve cached itemsitemsPublic Function GetProductData() As DataSet If (IsNothing(Cache("ProductData")) Then Cache("ProductData") = LoadDataSet() Return Cache("ProductData")End Function

19
Cache DependenciesCache Dependencies
File-based dependenciesFile-based dependencies Cached item invalidated when files changeCached item invalidated when files change
Key-based dependenciesKey-based dependencies Cached item invalided when another cached item Cached item invalided when another cached item
changeschanges
Time-based dependenciesTime-based dependencies Absolute time-based invalidationsAbsolute time-based invalidations Sliding time-based invalidationsSliding time-based invalidations

20
Scavenging MemoryScavenging Memory
Automatic system that initiates when memory Automatic system that initiates when memory becomes scarcebecomes scarce
Tag cached items with relative importanceTag cached items with relative importance CacheItemPriority CacheItemPriority CacheItemPriorityDecayCacheItemPriorityDecay
Items must be added to cache using .Add Items must be added to cache using .Add or .Insert to make use of these enumerationsor .Insert to make use of these enumerations

21
Using Callbacks with CachingUsing Callbacks with Caching
Create Callbacks with this delegate:Create Callbacks with this delegate:
CacheItemRemovedCallbackCacheItemRemovedCallback Callbacks are used to receive notification Callbacks are used to receive notification
when an item is evicted from the cachewhen an item is evicted from the cache CleanupCleanup UpdateUpdate RecreateRecreate LoggingLogging
Items must be added to caching using .Add Items must be added to caching using .Add or .Insert to use callback functionalityor .Insert to use callback functionality

22
ReviewReview
Code that uses items from the data cache Code that uses items from the data cache must be able to create the object, load the must be able to create the object, load the cache, or retrieve the object before using it.cache, or retrieve the object before using it.
Caching can hide problems. Test without Caching can hide problems. Test without caching.caching.
Use tracing, performance counters, and Use tracing, performance counters, and stress software to identify caching wins.stress software to identify caching wins.

23
Additional Information about Additional Information about CachingCaching INFO: ASP.NET Caching OverviewINFO: ASP.NET Caching Overview HOW TO: Control Page Output Caching in ASHOW TO: Control Page Output Caching in AS
P.NET by Using Visual Basic .NET P.NET by Using Visual Basic .NET HOW TO: Perform Fragment Caching in ASP.HOW TO: Perform Fragment Caching in ASP.
NET by Using Visual Basic .NET NET by Using Visual Basic .NET

Thank you for joining today’s Microsoft SupportThank you for joining today’s Microsoft Support
WebCast.WebCast.
For information about all upcoming Support WebCasts, For information about all upcoming Support WebCasts,
and access to the archived content (streaming mediaand access to the archived content (streaming media
files, PowerPointfiles, PowerPoint®® slides, and transcripts), please visit: slides, and transcripts), please visit:
http://http://support.microsoft.com/webcastssupport.microsoft.com/webcasts//
Your feedback is sincerely appreciated. Please send any Your feedback is sincerely appreciated. Please send any
comments or suggestions about the Support comments or suggestions about the Support
WebCasts to WebCasts to [email protected]@microsoft.com. .