Lesson 3: Caching Application Data

Lesson 3: Caching Application Data

In addition to Web form and fragment caching, you can also cache any frequently used application data. In general, cached application data is considered read-only, because it reflects a copy of information stored elsewhere. However, you can use the CacheItemRemovedCallback delegate to store changes to cached data before they are unloaded from memory.

After this lesson, you will be able to

  • Use the Cache object to store and retrieve application data

  • Specify how long an item remains in the cache

  • Remove an item from the cache

  • Detect when a cached item is about to be removed from memory

  • Establish a dependency between a cached item and an external source, such as a data file

Estimated lesson time: 15 minutes

Using the Cache Object

Use the intrinsic Cache object to store frequently used items in the server s memory for quick retrieval. The Cache object is global that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.

There are several ways to store data in the Cache object:

  • Use assignment.

    Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. Assigning a value to a key that already exists replaces the cached value with the assigned value.

  • Use the Insert method.

    The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.

  • Use the Add method.

    The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.

For example, the following Cache statements all add the same item to the cache:

Visual Basic .NET

' At module-level: Imports System.Web.Caching Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then Cache("NewItem") = "Some string data" Cache.Add("NewItem", "Some string data", Nothing, _ Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), _ Caching.CacheItemPriority.Default, Nothing) Cache.Insert("NewItem", "Some string data") End If End Sub

Visual C#

// At module-level using System.Web.Caching; private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { Cache["NewItem"] = "Some string data"; Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null); Cache.Insert("NewItem", "Some string data"); } }

Table 12-4 describes the parameters used by the Cache object s Insert and Add methods.

Table 12-4. Parameters for the Cache Object s Insert and Add methods

Parameter

Description

key

The identifier used to access the cached data.

value

The data to cache.

dependencies

A CacheDependency object that references a file used to track changes to data outside of the cache. Use dependencies to synchronize data in the cache with data stored elsewhere.

absoluteExpiration

A DateTime object that identifies when the data should be removed from the cache. If you re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.

slidingExpiration

A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.

priority

A CacheItemPriority enumeration value identifying the relative priority of the cached data.

onRemoveCallback

A delegate to call when the data is removed from the cache. Use onRemoveCallback to notify the application when items are removed from the cache.

You access cached data through the item s key, just as you did with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:

Visual Basic .NET

Private Sub Page_PreRender(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.PreRender ' Display value: If IsNothing(Cache("NewItem")) Then lblNewItem.Text = "NewItem not found." Else lblNewItem.Text = Cache("NewItem") End If End Sub

Visual C#

private void DataCache1_PreRender(object sender, EventArgs e) { // Display value: if (Cache["NewItem"] == null) lblNewItem.Text = "NewItem not found."; else lblNewItem.Text = Cache["NewItem"].ToString(); }

To remove data from the cache, use the Cache object s Remove method. For example, the following code removes the cache item used in the preceding code:

Visual Basic .NET

Private Sub butRemove_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butRemove.Click Cache.Remove("NewItem") End Sub

Visual C#

private void butRemove_Click(object sender, System.EventArgs e) { Cache.Remove("NewItem"); }

Controlling How Long Data Is Cached

The Cache object s Add and Insert method parameters allow you to control how long an item is stored in the server s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.

Use the Add or Insert method s priority parameter to set the relative importance of cached items. Table 12-5 lists the priority settings in order from highest to lowest.

Table 12-5. Cache Priority Settings

Setting

Comment

CacheItemPriority.NotRemoveable

Highest priority.

CacheItemPriority.High

CacheItemPriority.AboveNormal

CacheItemPriority.Normal, CacheItemPriority.Default

Normal and Default are the same.

CacheItemPriority.BelowNormal

CacheItemPriority.Low

Lowest priority; item is likely to be removed.

Responding to Cache Events

The Add and Insert methods onRemoveCallback parameter allows you to associate a callback function to run when the item is removed from the cache. This is the only event that the Cache object provides.

The following code uses the CacheItemRemovedCallback delegate to display information about a cache item before it is removed. The code associated with the callback is shown in boldface for clarity.

Visual Basic .NET

Imports System.Web.Caching Public Class DataCache1 Inherits System.Web.UI.Page Dim onRemove As CacheItemRemovedCallback Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then onRemove = New CacheItemRemovedCallback(AddressOf RemovedCallback) Cache.Add("NewItem", "Some string data", Nothing, _ Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), _ Caching.CacheItemPriority.Default, onRemove) End If End Sub Private Sub butRemove_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butRemove.Click Cache.Remove("NewItem") End Sub Public Sub RemovedCallback(ByVal key As String, ByVal value As Object, _ ByVal reason As System.Web.Caching.CacheItemRemovedReason) Cache("Status") = "Cache item: " + key + " value: "_  + value.ToString() + " was " + reason.ToString End Sub  Private Sub Page_PreRender(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.PreRender ' Display status. If Not IsNothing(Cache("Status")) Then _ lblStatus.Text = Cache("Status").ToString End Sub End Class

Visual C#

using System.Web.Caching; namespace MCSDWebAppsCS { public class DataCache1 : System.Web.UI.Page { CacheItemRemovedCallback onRemove;  private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { onRemove = new CacheItemRemovedCallback(this.RemovedCallback); Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, onRemove); } } void RemovedCallback(string key, Object value , CacheItemRemovedReason reason) { Cache["Status"] = "Cache item: " + key + " value: " + value.ToString() + " was " + reason.ToString(); }  private void butRemove_Click(object sender, System.EventArgs e) { Cache.Remove("NewItem"); } private void DataCache1_PreRender(object sender, EventArgs e) { // Display status. if (Cache["Status"] != null) lblStatus.Text = Cache["Status"].ToString(); } } }

Updating the Cache When Data Changes

Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.

The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.

For example, the following code creates a cache item with a dependency. When the user clicks the Change button, the time stamp on the Newitem.txt file is changed, causing ASP.NET to remove NewItem from the cache.

Visual Basic .NET

Imports System.Web.Caching Public Class DataCache2 Inherits System.Web.UI.Page Dim strFile As String = Server.MapPath(".") + "\NewItem.txt" Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then Cache.Add("NewItem", "Some cached data with a dependency.", _ New CacheDependency(strFile, Now()), Cache.NoAbsoluteExpiration, _ System.TimeSpan.FromMinutes(1), _ Caching.CacheItemPriority.Default, null) End If End Sub Private Sub butChange_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butChange.Click System.IO.File.SetLastWriteTime(strFile, Now) End Sub Private Sub Page_PreRender(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.PreRender ' Display value: If IsNothing("NewItem") Then lblNewItem.Text = "NewItem not found." Else lblNewItem.Text = Cache("NewItem") End If End Sub End Class

Visual C#

using System.Web.Caching; namespace MCSDWebAppsCS { { string strFile = ""; private void Page_Load(object sender, System.EventArgs e) { strFile = Server.MapPath(".") + "\\NewItem.txt"; if(!IsPostBack) { Cache.Add("NewItem", "Some string data", new CacheDependency(strFile, System.DateTime.Now), Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, onRemove); } } private void butChange_Click(object sender, System.EventArgs e) { System.IO.File.SetLastWriteTime(strFile, System.DateTime.Now); } private void DataCache2_PreRender(object sender, EventArgs e) { // Display value: if (Cache["NewItem"] == null) lblNewItem.Text = "NewItem not found."; else lblNewItem.Text = Cache["NewItem"].ToString(); } } }



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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