Advanced ASP.NET : Data Caching (part 1) - Adding Items to the Cache & A Simple Cache Test

2/19/2011 4:16:32 PM
Data caching is the most flexible type of caching, but it also forces you to take specific additional steps in your code to implement it. The basic principle of data caching is that you add items that are expensive to create to a built-in collection object called Cache. Cache is a property of the Page class, and it returns an instance of the System.Web.Caching.Cache class. This object is globally available to all requests from all clients in the application. But it has three key differences:
The Cache object is thread-safe:

This means you don't need to explicitly lock or unlock the Cache object before adding or removing an item. However, the objects in the Cache object will still need to be thread-safe themselves. For example, if you create a custom business object, more than one client could try to use that object at once, which could lead to invalid data. You can code around this limitation in various ways—one easy approach that you'll see in this article is to just make a duplicate copy of the object if you need to work with it in a web page.

Items in the Cache object are removed automatically:

ASP.NET will remove an item if it expires, if one of the objects or files it depends on changes, or if the server becomes low on memory. This means you can freely use the cache without worrying about wasting valuable server memory, because ASP.NET will remove items as needed. But because items in the cache can be removed, you always need to check whether a cache object exists before you attempt to use it. Otherwise, you could generate a null reference exception.

Items in the cache support dependencies:

You can link a cached object to a file, a database table, or another type of resource. If this resource changes, your cached object is automatically deemed invalid and released.

1. Adding Items to the Cache

You can insert an object into the cache in several ways. You can simply assign it to a new key name (as you would with the Session or Application collection):

Cache("KeyName") = objectToCache

However, this approach is generally discouraged because it doesn't give you any control over the amount of time the object will be retained in the cache. A better approach is to use the Insert() method.

The Insert() method has four overloaded versions. The most useful one requires five parameters:

Cache.Insert(key, item, dependencies, absoluteExpiration, slidingExpiration)

Table 1 describes these parameters.
Table 1. Cache.Insert() Parameters
keyA string that assigns a name to this cached item in the collection and allows you to look it up later.
itemThe actual object you want to cache.
dependenciesA CacheDependency object that allows you to create a dependency for this item in the cache. If you don't want to create a dependent item, just specify a null reference (Nothing) for this parameter.
absoluteExpirationA DateTime object representing the date and time at which the item will be removed from the cache.
slidingExpirationA TimeSpan object representing how long ASP.NET will wait between requests before removing a cached item. For example, if this value is 20 minutes, ASP.NET will evict the item if it isn't used by any code for a 20-minute period.

Typically, you won't use all of these parameters at once. You cannot set both a sliding expiration and an absolute expiration policy at the same time. If you want to use an absolute expiration, set the slidingExpiration parameter to TimeSpan.Zero:

Cache.Insert("MyItem", obj, Nothing, _
DateTime.Now.AddMinutes(60), TimeSpan.Zero)

Absolute expirations are best when you know the information in a given item can be considered valid only for a specific amount of time (such as a stock chart or a weather report). Sliding expiration, on the other hand, is more useful when you know that a cached item will always remain valid (such as with historical data or a product catalog) but should still be allowed to expire if it isn't being used. To set a sliding expiration policy, set the absoluteExpiration parameter to DateTime.MaxValue, as shown here:

Cache.Insert("MyItem", obj, Nothing, _
DateTime.MaxValue, TimeSpan.FromMinutes(10))

Don't be afraid to cache for a long time. For example, Microsoft's case studies often store cached data for 100 minutes or more.

2. A Simple Cache Test

The following page presents a simple caching test. An item is cached for 30 seconds and reused for requests in that time. The page code always runs (because the page itself isn't cached), checks the cache, and retrieves or constructs the item as needed. It also reports whether the item was found in the cache.

Public Partial Class SimpleDataCache
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load

If Me.IsPostBack Then
lblInfo.Text &= "Page posted back.<br />"
lblInfo.Text &= "Page created.<br />"
End If

If Cache("TestItem") Is Nothing Then
lblInfo.Text &= "Creating TestItem...<br />"
Dim testItem As DateTime = DateTime.Now

lblInfo.Text &= "Storing TestItem in cache "
lblInfo.Text &= "for 30 seconds.<br />"
Cache.Insert("TestItem", testItem, Nothing, _
DateTime.Now.AddSeconds(30), TimeSpan.Zero)
lblInfo.Text &= "Retrieving TestItem...<br />"
Dim testItem As DateTime = CType(Cache("TestItem"), DateTime)
lblInfo.Text &= "TestItem is '" & testItem.ToString()
lblInfo.Text &= "'<br />"
End If

lblInfo.Text &= "<br />"
End Sub

End Class

Figure 1 shows the result after the page has been loaded and posted back several times in the 30-second period.

Figure 1. A simple cache test
PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Top 10 Video Game
-   Anno 2025 - E3 2015 Intro Trailer
-   Awesome GTA V Sniper Chopper Kill
-   Awesome GTA V Parachute Video
-   GTA V Explosive Ammo Rounds with Bikini
-   Funny GTA V Road Rage Clip
-   Cool GTA V Motorbike Jump
-   When a Mouse Jacks Your Truck in GTA V
-   Pig Riding a Motorbike in GTA V
-   Using an Uzi While Driving in GTA V
-   PlayStation 4 Ultimate Player 1TB Edition | Reveal Announcement
-   Dreamfall Chapters Book Three: Realms [PC] Zoe Trailer
-   Street Fighter V Trailer
-   Beyond Flesh and Blood | Beetham Folly Gameplay 1
-   Uncharted 4: A Thief's End | E3 2015 Gameplay Demo PS4
-   World of Warcraft | Patch 6.2 Survival Guide
Game of War | Kate Upton Commercial