An overview of Caching in ASP.NET

By Mohammad Mahdi Ramezanpour at August 11, 2008 11:08
Filed Under: ASP.NET, Web design

Centered around the Cache object, the ASP.NET caching API is much more than simply a container of global data shared by all sessions. Preserved for backward compatibility with classic ASP applications, the Application intrinsic object presents itself as a global container of data with an indexer property and a user-callable locking mechanism. The Cache object is a smarter and thread-safe container that can automatically remove unused items, support various forms of dependencies, and optionally provide removal callbacks and priorities.

The Application object is maintained for backward compatibility with legacy applications; new ASP.NET applications should use the Cache object.

The Cache Class

The Cache class is exposed by the System.Web.Caching namespace and is a new entry in the set of tools that provide state management in ASP.NET. The Cache class works like an application-wide repository for data and objects, but this is the only aspect that it has in common with the HttpApplicationState class, as we'll see in a moment.

An instance of the Cache class is created on a per-AppDomain basis and remains valid until that AppDomain is up and running. The current instance of the application's ASP.NET cache is returned by the Cache property of the HttpContext object or the Cache property of the Page object.

Cache and Other State Objects

In spite of their common goal—to serve as a global data repository for ASP.NET applications—Cache and HttpApplicationState classes are quite different. Cache is a thread-safe object and does not require you to explicitly lock and unlock before access. All critical sections in the internal code are adequately protected using synchronization constructs. Another key difference with the HttpApplicationState class is that data stored in Cache doesn't necessarily live as long as the application does. The Cache object lets you associate a duration as well as a priority with any of the items you store.

Any cached item can be configured to expire after a specified number of seconds, freeing up some memory. By setting a priority on items, you help the Cache object to select which items can be safely disposed of in case of memory shortage. Items can be associated with various types of dependencies, such as the timestamp of one or more files and directories, changes on other cached items, database table changes, and external events. When something happens to break the link, the cached item is invalidated and is no longer accessible by the application.

Both Cache and HttpApplicationState are globally visible classes and span all active sessions. However, neither works in a Web farm or Web garden scenario; in general, they don't work outside the current AppDomain.

  Note 

When more than one AppDomain is involved (for example, in a Web farm), presumably all AppDomains would contain the same cached data, assuming that the cached information is not dynamic. Unlike with session state, this isn't too troubling because the assumption is that application-wide static values can be read upon initialization and cache timeout. If the cached information is dynamic, that's a different story. In that case, you should consider a global cross-machine container, as we'll discuss shortly.

The Cache object is unique in its capability to automatically scavenge the memory and get rid of unused items. Aside from that, it provides the same dictionary-based and familiar programming interface as Application and Session. Unlike Session, the Cache class does not store data on a per-user basis. Furthermore, when the session state is managed in-process, all currently running sessions are stored as distinct items in the ASP.NET Cache.

  Note 

If you're looking for a global repository object that, like Session, works across a Web farm or Web garden architecture, you might become frustrated. No such object exists in the Microsoft .NET Framework. To build a cross-machine container, you need to resort to a shared and remote resource, such as an external service or perhaps an installation of Microsoft SQL Server or another database. This means that each access to data will require serialization and is subject to network latency. In general, this scheme is complex enough to invalidate most of the advantages you get from data caching. As far as caching is involved, the tradeoff to evaluate is accessing ready-made data versus running the query to fetch a fresh copy of desired data. ASP.NET provides an effective infrastructure for caching data locally because that is what you need most of the time. Adding to the infrastructure to cover Web farms is up to you.

 

An instance of the Cache object is associated with each running application and shares the associated application's lifetime. The cache holds references to data and proactively verifies validity and expiration. When the system runs short of memory, the Cache object automatically removes some little-used items and frees valuable server resources. Each item—when stored into the cache—can be given special attributes that determine a priority and an expiration policy. All these are system-provided tools to help programmers control the scavenging mechanism of the ASP.NET cache.

Inserting New Items in the Cache

A cache item is characterized by a handful of attributes that can be specified as input arguments of both Add and Insert. In particular, an item stored in the ASP.NET Cache object can have the following properties:

  • Key. A case-sensitive string, it is the key used to store the item in the internal hashtable the ASP.NET cache relies upon. If this value is null, an exception is thrown. If the key already exists, what happens depends on the particular method you're using: Add fails, while Insert just overwrites the existing item.

  • Value. A non-null value of type Object that references the information stored in the cache. The value is managed and returned as an Object and needs casting to become useful in the application context.

  • Dependencies. Object of type CacheDependency, tracks a physical dependency between the item being added to the cache and files, directories, database tables, or other objects in the application's cache. Whenever any of the monitored sources are modified, the newly added item is marked obsolete and automatically removed.

  • Absolute Expiration Date. A DateTime object that represents the absolute expiration date for the item being added. When this time arrives, the object is automatically removed from the cache. Items not subject to absolute expiration dates must use the NoAbsoluteExpiration constants representing the farthest allowable date. The absolute expiration date doesn't change after the item is used in either reading or writing.

  • Sliding Expiration. A TimeSpan object, represents a relative expiration period for the item being added. When you set the parameter to a non-null value, the expiration-date parameter is automatically set to the current time plus the sliding period. If you explicitly set the sliding expiration, you cannot set the absolute expiration date, too. From the user's perspective, these are mutually exclusive parameters. If the item is accessed before its natural expiration time, the sliding period is automatically renewed.

  • Priority. A value picked out of the CacheItemPriority enumeration; it denotes the priority of the item. It is a value ranging from Low to NotRemovable. The default level of priority is Normal. The priority level determines the importance of the item; items with a lower priority are removed first.

  • Removal Callback. If specified, indicates the function that the ASP.NET Cache object calls back when the item will be removed from the cache. In this way, applications can be notified when their own items are removed from the cache no matter what the reason is. When the session state works in InProc mode, a removal callback function is used to fire the Session_End event. The delegate type used for this callback is CacheItemRemoveCallback.

There are basically three ways to add new items to the ASP.NET Cache object—the set accessor of Item property, the Add method, and the Insert method. The Item property allows you to indicate only the key and the value. The Add method has only one signature that includes all the aforementioned arguments. The Insert method is the most flexible of all options and provides the following four overloads:

	public void Insert(string, object);public void Insert(string, object, CacheDependency);
	public void Insert(string, object, CacheDependency, DateTime, TimeSpan);
	public void Insert(string, object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback);

The following code snippet shows the typical call that is performed under the hood when the Item set accessor is used:

Insert(key, value, null, Cache.NoAbsoluteExpiration,    Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

If you use the Add method to insert an item whose key matches that of an existing item, no exception is raised, nothing happens, and the method returns null.

Comments

7/14/2009 11:58:07 PM #

Betsey Johnson

Hmm strange this post is totaly irrelevant to the search query I entered in google but it was listed on the first page.

Betsey Johnson United States

7/15/2009 6:24:50 AM #

Dell Laptop Xps

I appreciate this wonderful blog.

Dell Laptop Xps United States

7/18/2009 1:43:13 PM #

Lån Online

Nice way of summing it up.. cheers

Lån Online

7/19/2009 4:29:04 PM #

запознанства

Thank you, for the source Smile Cheers!

запознанства

7/19/2009 4:55:44 PM #

Hoodia

Thanks - Just the info I was looking for.. My search ends here..

Hoodia

7/19/2009 10:10:04 PM #

запознанства

10x for the code Smile Cheers!

запознанства

7/25/2009 11:37:56 AM #

San Diego Web Design

Great, great, great and - did I forget something? Oh, yeah: Great! thanks for sharing that with us. BTW: I'm typing this on my new iphone - cool...

San Diego Web Design United States

7/25/2009 11:38:00 AM #

Duck Hunting Canada

This was refreshing. I wished I could read every post, but i have to go back to work... But I'll be back.

Duck Hunting Canada United States

7/31/2009 1:06:59 PM #

hunting

Thank you so much for a wonderful blog. I have read some of your blogs and I share it with my friends. They want to say thank you to you as well.

hunting United States

8/2/2009 4:43:25 AM #

Learn Master Guitar

Cool! Wouldn't mind reading more of this. You got some nice resources here - going to bookmark some of your pages. Thanks!

Learn Master Guitar United States

8/4/2009 7:51:43 AM #

Make Your Own Website

Admiring the time and effort you put into your blog and detailed information you offer! I didn't know that!

Make Your Own Website United States

8/5/2009 12:23:27 AM #

one minute cure for cancer

I was looking for something different on Google, but ended here, reading your blog post, good read, thanks. Smile

one minute cure for cancer United States

8/5/2009 8:41:09 AM #

Learn German

Admiring the time and effort you put into your blog and detailed information you offer! I didn't know that!

Learn German United States

8/8/2009 9:52:56 PM #

cool game

Is this better than wp?

cool game United Kingdom

8/8/2009 9:53:00 PM #

hard games

Looks tight man keep up good work on this, I found this site via Google.

hard games United Kingdom

Comments are closed

Currently Reading

Quote of the day

Send Persian SMS