The Cache API

Many of my classic ASP applications use session and application variables to store data that's used often. This approach can dramatically improve an application's performance because database queries (and other methods of data retrieval) can be done at session or application start, and not every time the application needs the data. Of course, you have to make sure you're loading data that's actually used enough to warrant the pre-loading.

This method only works with data that's constant. If you cache data that changes often, it will not be current and thus not valid when your application uses it. With clever classic ASP programming, however, an application can watch for changes in data that change infrequently without incurring too much overhead.

Of course, there's a price for caching data that price is called memory. For every piece of cached data, a chunk of memory is committed for as long as the data is cached. You probably wouldn't cache your entire product catalog, but you would very likely cache something small, such as a list of states with which a selection list is populated.

The ASP.NET Cache object offers much more than the session and application variable caching that was so popular in classic ASP programming. Cached objects can expire in several ways, giving you great flexibility. Three methods, Add(), Insert(), and Remove(), offer an easier way to manipulate items. And you can even find out what type of object is cached with the GetType() method.

This section will show you how to use the Cache object, and this in turn will offer you a great way to improve your application's performance.

Cache objects maintain state on a per-domain basis. That means each domain can share cached data between various applications that reside inside of the domain, and between all the users in the domain.

Enumerating Cache Items

We'll first take a look at enumerating the cached objects that a server is maintaining for the domain. Each page has a Cache property. As the application walks through the list of Cache items, DictionaryEntry objects are returned for each cached object found. The DictionaryEntry object has a Key property, which can be used to obtain the object contents from the Cache object. Listing 4.11 shows code that enumerates the items that are currently cached in the domain.

Listing 4.11 This Code Shows All Objects That Are Cached in the Current Domain.

C#

 string strCacheContents; string strName; strCacheContents = "<b>The ASP.NET application cache contains:</b><br/>"; foreach( DictionaryEntry objItem in Cache ) {     strName = objItem.Key.ToString();     // Skip System-created cache objects and look for ones     //   that were created by applications.     if( strName.Substring( 0, 7 ) != "System.")     {         strCacheContents = strName + " + " + Cache[strName].ToString() +           "<br/>";         Response.Write( strCacheContents );     } } 

VB

 Dim strCacheContents As String Dim objItem As DictionaryEntry Dim strName as String strCacheContents = "<b>The ASP.NET application cache contains:</b><br/>" For Each objItem In Cache    strName = objItem.Key    If Left(strName, 7) <> "System." Then       strCacheContents = "key=" & strName & "<br />"       Response.Write(strCacheContents)        strCacheContents = "value=" & Convert.ToString(objItem.Value) & _          "<br/>"        Response.Write(strCacheContents)    End If Next 

Expiration Types

There are two types of Cache expiration: absolute and sliding. Absolute expiration causes a Cache object to expire after a specific time has elapsed, such as five minutes. If you want some data to expire once a day to reflect changes that may have to go into effect, you can set the expiration time for 24 hours.

Sliding expiration causes a Cache object to expire after the object hasn't been accessed for a certain time period. If a Cache object has a sliding expiration of 15 minutes, it won't expire until it hasn't been accessed for 15 minutes. For an example, see the code snippet labeled "Cache Example 1."

Adding, Inserting, and Removing Cache Items

The Cache object provides three methods that make manipulating objects easy: these are the Add(), Insert(), and Remove() methods. This section talks about these three methods.

The Add() Method

The Add() method adds the specified item to the Cache object with dependencies and expiration and priority policies. The method uses seven arguments: key, value, dependencies, absolute expiration, sliding expiration, priority, and a removal callback. The key is a string that identifies the object that you're placing into the cache, such as "ListOfStates". If a key with this name already exists in the cache, the Add() method will fail.

The value parameter can be any object that you want to place in the cache. The dependency parameter contains either a file or a key dependency. If, for instance, you have a key dependency of "ListOfCounties" and the Cache object with the key "ListOfCounties" expires, any key that you add with this as a dependency will expire also.

The priority parameter determines the urgency with which cached items are evicted from the list. The higher the priority, the closer to the exact expiration time that an object is likely to be removed from the cache. Table 4.2 shows the priorities that can be used.

Table 4.2. Priorities for Cache Objects

Priority

Description

AboveNormal

Cache items with this priority level are less likely to be deleted as the server frees system memory than those assigned a Normal priority.

BelowNormal

Cache items with this priority level are more likely to be deleted from the cache as the server frees system memory than items assigned a Normal priority.

Default

The default value for a cached item's priority is Normal.

High

Cache items with this priority level are the least likely to be deleted from the cache as the server frees system memory.

Low

Cache items with this priority level are the most likely to be deleted from the cache as the server frees system memory.

Normal

Cache items with this priority level are likely to be deleted from the cache as the server frees system memory only after those items with Low or BelowNormal priority. This is the default.

NotRemovable

The cache items with this priority level will not be deleted from the cache as the server frees system memory.

The last parameter for the Add() method allows you to specify a delete to handle an object's expiration. This doesn't apply to ASP.NET applications because they do not contain code that can be called as a delegate between page requests.

The following example demonstrates how to add an item to the cache with an absolute expiration five minutes from the current time, no sliding expiration, a priority of high, and no notification delegate.

Cache Example 1

C#

 Cache.Add( "MyName", objSomeObject, null, DateTime.Now.AddMinutes( 15 ),   null, CacheItemPriority.High, null ); 

VB

 Cache.Add("MyName", objSomeObject, Nothing, _   DateTime.Now.AddMinutes( 15 ), Nothing, _   CacheItemPriority.High, Nothing) 
The Insert() Method

The Insert() method puts an object into the cache but overwrites any objects currently in the cache with the same key. You would use the Insert() method if you wanted to update an object in the cache.

The following example shows how to use one of the overloaded versions of Insert(). It caches a DSN connection string for two minutes from the current time, using sliding expiration. This particular example provides a callback method that is fired when the Cache object expires.

C#
 Cache.Insert( "DSN", connectionString, null, DateTime.Now.AddMinutes(2),   TimeSpan.Zero, CacheItemPriority.High, onRemove ); 
VB
 Cache.Insert("DSN", connectionString, Nothing, _   DateTime.Now.AddMinutes(2), TimeSpan.Zero,_   CacheItemPriority.High, onRemove ) 
The Remove() Method

The Remove() method requires a single parameter, the key. This method removes the object from the cache that matches the key.

The following example demonstrates how you can remove an item from your application's Cache object:

C#
 Cache.Remove( "timestamp" ); 
VB
 Cache.Remove( "timestamp" ) 

RECOMMENDED PRACTICE: The above code, though, suggests a problem that could arise when you're using named Cache objects. You could inadvertently mistype in one place in your code, and then things won't work. The following could prevent typos in your code:

C#
 public const String CacheObjectName = "timestamp"; Cache.Remove( CacheObjectName ); 
VB
 public const CacheObjectName As String = "timestamp" Cache.Remove( CacheObjectName ) 


Using Cache Items

The Get() method retrieves an object given a key. If the object isn't found in the cache, a null is returned (or Nothing in VB). The GetType() method returns the runtime type of the object.



ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

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