Cache to specify http cache headers contains a

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: <%@ OutputCache Duration="60“ VaryByParam="none" %> Can cache multiple versions of a page, by: GET/POST parameters; use VaryByParam HTTP header; use VaryByHeader E.g. Accept-Language Browser type or custom string; use VaryByCustom Caching Caching in the Browser Don’t confuse server-side page output caching with how the browser and proxy servers cache the page Use Response.Cache to specify HTTP cache headers Contains a HttpCachePolicy object 20 Caching Data Caching Data cache is similar to application variables Can cache objects, HTML fragments, etc. Usage pattern: Try to retrieve data If null then create data and insert into cache DataView Source = (DataView)Cache["MyData"]; if (Source == null) { Source = new DataView(ds.Tables["Authors"]); Cache["MyData"] = Source; // Save in cache } Caching Data Caching Cache object is stored on the Page and is an instance of System.Web.Caching.Cache 21 Caching Data Caching Cache may be scavenged: when memory runs low it will be automatically reclaimed Can specify data expiration: absolute time (e.g. midnight), relative (in 1 hour) Cached data can be dependent upon a file or other cache item Cache.Insert("MyData", Source, null, // Expire in 1 hour DateTime.Now.AddHours(1), TimeSpan.Zero); Cache.Insert("MyData", Source, // Dependent on file new CacheDependency(Server.MapPath("authors.xml"))); Caching Data Caching Populating a data cache has an inherent race condition: if hit almost concurrently, multiple pages may try to populate the same cache This probably doesn’t matter at all; it’s only significant if the cost to create the data is prohibitive or if there are side effects If it does matter, there are two solutions: Populate the cache in Application_OnStart Synchronize access to the cache 22 Caching Data Caching private static String cacheSynchronize = "myKey"; DataView Source = (DataView)Cache["MyDataSet"]; if (Source == null) { lock (cacheSynchronize) { Source = (DataView)Cache["MyDataSet"]; if (Source == null) { // Have to test again // Open database ... Source = new DataView(ds.Tables["Authors"]); Cache["MyDataSet"] = Source; // Save in cache } } } View State ASP.NET page state maintenance is great, but __VIEWSTATE can get quite large Why store constant data in __VIEWSTATE? E.g. dropdowns listing countries, states, days...
View Full Document

Ask a homework question - tutors are online