A new option for maintaining state in ASP.NET is caching of data with the Cache object.
The Cache object works in a similar way to the other state management objects covered in this chapter in that it too stores data in key-value pairs. The Cache object closely resembles the Application object because state can be maintained throughout the life of the application and is private to each application. The downside is that any data stored there will be lost if the application is recycled.
The following syntax can be used in a regular ASP.NET page to store data in the Cache object:
Cache("Key") = Value
The following syntax can be used in a regular ASP.NET page to retrieve data from the Cache object:
Value = Cache("Key")
Up to now, this looks identical to the Application object. So what is the added value of the Cache object?
The cache object provides more sophisticated functionality, allowing more advanced applications to take advantage of file and key dependencies, cache expiration, and scavenging.
File and key dependencies allow developers to specify an external file or another cached item to be validated against. The validity of a cache item is based on whether the external file has been modified (or deleted) or if the dependant cache item has been changed. If a dependency changes, the cache item is invalidated and removed from the cache.
An example of how file and key dependencies could be used is an application that has any form of dynamic information (financial information, weather, and so on) that is generated periodically and cached in an XML file. The application processes and displays the data. Keeping it up-to-date is of utmost importance. A cache item can be inserted containing this information, and a dependency on the file from which the data was read can be created. When the file is updated, the data is removed from the cache and the application can reread it and reinsert the updated copy of the data.
Cache expiration allows developers to give cached information a limited lifetime. The lifetime of a cache item can be defined as explicit (a time is specified) or relative to an item's last use (a time span is specified).
After an item has expired, it is removed from the cache. Any future attempts to retrieve a cached item after it has been removed will result in a null value being returned unless the item is reinserted into the cache.
An example of how cache expiration could be used is in a stock ticker application that receives stock prices every two minutes. Between the intervals there is no need to retrieve the information from its original source since this information is readily available in the cache.
Scavenging is the automated cleanup process of infrequently used or less important information.
When entering a piece of information into the Cache, you can specify how ASP.NET should scavenge the data. That is, you can specify the cost of creating the item and the relative rate at which the item should be accessed. As soon as ASP.NET recognizes that a certain cached item has not been accessed for a lengthy amount of time, or is less expensive to create than other cached items, it will remove this item of this cache.
An example of how scavenging could be used is an application performing lengthy calculations to speed up the process allowing for frequently calculated information to be cached. As the cache grows, the less expensive items will be disposed of, while the more expensive items can be retained in memory for continued use.
Within ASP.NET, the Cache object is exposed as a property of the Page object. Accessing the Cache object from a Web Service is a little different to the Application and Session objects, in that the Cache object cannot be accessed directly. To receive information from the Cache class, the Cache property of the HttpContext object will be used. The Web Service object exposes an HttpContext property.
Because the Cache object's Add method is overloaded, we will start from the simplest method call and work up from there.
The following is the syntax that can be used to insert an object into the cache:
Me.Context.Cache.Insert(<key>, <value>)
The term key identifies the item cached. The value of the key is defined by the developer and is identical to the key attribute of the Session and Application objects (receives a string value).
The value term specifies the item to be cached. This, too, is identical to that of the Session and Application object in that it can receive any object type.
An important issue to keep in mind when using the Cache object (and any of the other state objects) is the chance that this object may not yet exist in memory or may have been removed. Before attempting to retrieve a value from the Cache object, check that the value is not Nothing.
The following is common syntax for retrieving data from the Cache object:
If Me.Context.Cache.Item("key") Is Nothing Then ' Do Something! Else CacheSearch = Me.Context.Cache.Item("key") End If
As you can see, the retrieval is also a little different from that of the Session and Application objects.
Next let's take a look at how a file and key dependency can be specified for a cached item.
The following is the syntax that can be used to insert an object into the cache while specifying a dependant file:
Me.Context.Cache.Insert(<key>, <value>, <dependencies>)
The dependencies parameter specifies the file or cache key of a dependant cache item. If there are no dependencies, this parameter should be set to Nothing.
Me.Context.Cache.Insert("CalculatedInfo", Source, _ New CacheDependency(Server.MapPath("financial.xml")))
A cached item can have single or multiple dependencies. These dependencies can include one or more files or cached item keys.
Cache expiration can prove to be very useful. Unused information can be removed from memory so resources are conserved.
The following is the syntax that can be used to insert an object into the cache while specifying cache expiration:
Me.Context.Cache.Insert(<key>, <value>, <dependencies>, <absoluteExpiration>, <slidingExpiration>)
The absoluteExpiration property specifies the time at which the cached item expires and is removed from the cache. (This property is a DateTime variable type.)
The slidingExpiration property indicates the interval between the time the cached item was last accessed and when that object expires. If the value is set to 5 minutes, the cached item expires and is removed from the cache 5 minutes after it is last accessed. (This property is a TimeSpan variable type.)
The following is an example of how to set an absolute cache expiration time:
Me.Context.Cache.Insert("CalculatedInfo", Source, null, _ DateTime.Now.AddMinutes(90), _ TimeSpan.Zero)
In this example, the absoluteExpiration parameter is set using the DataTime.Now.AddMinutes(90) call, which specifies the expiration time of the cached item as 90 minutes after the item is inserted into the cache. The slidingExpiration parameter is set to Timespan.Zero, which indicates that there is no relative expiration policy on this cached item.
The following is an example of how to set a relative expiration policy:
Me.Context.Cache.Insert("CalculatedInfo", Source, null, _ DateTime.MaxValue, _ TimeSpan.FromMinutes(90))
In this example, the absoluteExpiration parameter is set using the DataTime.MaxValue, which specifies that there is no absolute expiration policy of this cached item. The slidingExpiration parameter is set to Timespan.FromMinutes(90), which indicates that the cached item should expire after 90 minutes.
Last, but definitely not least, we will look at the priority property that enables scavenging.
The following is the syntax that can be used to insert an object into the cache while specifying the priority:
Me.Context.Cache.Insert(<key>, <value>, <dependencies>, <absoluteExpiration>, <slidingExpiration>, <priority>, <onRemoveCallback>)
The priority parameter indicates the relative cost of the cached item. The cost is specified by the use of the CacheItemPriority enumeration.
The onRemoveCallback parameter is a delegate that can be provided to the Cache object so that the application can be notified if and when a cached item is removed from the cache.
The following is an example of how to set a priority:
Me.Context.Cache.Insert("CalculatedInfo", Source, null, _ DateTime.MaxValue, _ TimeSpan.Zero, _ CacheItemPriority.High, _ Nothing)
The priority has been set to CacheItemPriority.High so that this piece of information is removed last from the cache.
Some of the other CacheItemPriority values include the following:
NotRemovable Cache items with this priority level will not be removed from the cache as the server frees system memory.
High Cache items with this priority level are the least likely to be deleted from the cache as the server frees system memory.
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.
Default The default value for a cached item's priority is Normal.
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.
Low Cache items with this priority level are the most likely to be deleted from the cache as the server frees system memory.
Note that, as we have seen, not all of the parameters need to be passed into the call. Each type of parameter has its own null value for specifying if the specific policy is not implemented.
3.21.248.162