Caching in ASP.NET...
Caching is new to the .NET framework, and is a very useful utility for caching large amounts of data in memory.
Caching is new to the .NET framework, and is a very useful utility for caching large amounts of data in memory. It uses a key/value pair to enter information into the cache. All items are then referred to by this string. The cache supports methods to add, retrieve, and remove items from the cache, as well as support for priorities, dependencies and callback procedures. Caching also supports locking, which the cache object handles automatically. Whenever a request is using the cache, it is automatically locked from all other ASP.NET processes.
When items are added to the cache, a dependency or expiration property can be used to update or remove the content in the cache. Dependencies are based on a file, directory, or another cached item; if that item is altered, a Boolean value (HasChanged property) tracks the change, which can be detected in your code. In addition, specifying an expiration date or time can occur in two ways: using the AbsoluteExpiration or SlidingExpiration property. These properties accept a DateTime and a TimeSpan object, respectively. The first property accepts a date that the cached item will expire (i.e., 1/1/2005). If dated expiration is not desired, specify “Cache.NoAbsoluteExpiration” or “DateTime.MaxValue” for the parameter. In addition, the SlidingExpiration property accepts a time when the cached item will expire (20 minutes from now). If a timed expiration is not desired, specify “Cache.NoSlidingExpiration” or “TimeSpan.MaxValue”. You can specify one, both, or none expiration parameters, although it is recommended to choose one of the expiration options.
In addition to the features above, caching also supports memory management of cached items and callbacks. Memory management occurs by removing items with the lowest priorities, as specified by the CacheItemPriority enumeration, from the cache when new items are added and as is needed. It is a good idea to verify the existence of cached items before referencing them. Callback procedures can also be a useful feature, which tracks the removal of items. This parameter uses the CacheItemRemovedCallback class, which accepts a delegate function to execute upon the removal of a cached item. When the item is removed for any reason, this delegate is executed and passed the parameters of the name and value of the key, and a message stating the reason of the removal.
Below is an example of Caching in an ASP.NET web forms page. This is an example not for its practicality, but to show you the syntax for using caching in ASP.NET. The first routine is the page load method, which will verify that the contents of the cache exist, and that the page is loading for the first time. This is important, because at the initial page load (IsPostBack = False), the cached item should not exist. However, the situation can exist where the page could be posting back to the server (IsPostBack = True), but the cached item expired. In this situation, the Cached item must be recreated. Error handling is setup in the case that the cached item exists and the page is loading for the first time. This is not necessarily a bad thing; this is the logical flow for this particular application. If the item exists and the page is posting back, the value is retrieved and assigned to a textbox control.
In addition, when a cached item is removed, the CacheRemoved method is called. This can be from expiration or due to memory management removing an item from the cache to make space for another object.
|
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If (Not Page.IsPostBack Or IsNothing(Cache("MyCachedItem"))) Then 'No cached item exists, create one Try Cache.Add("MyCachedItem", TextBox1.Text, Nothing, _ Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20), _ CacheItemPriority.Low, New CacheItemRemovedCallback(AddressOf CacheRemoved)) Catch objEx As System.Exception lnkMessage.Text = objEx.ToString() lnkMessage.Visible = True End Try Else TextBox1.Text = Cache.Get("MyCachedItem").ToString() End If End Sub |
The CacheRemoved method takes three parameters: the key, which is the key used to retrieve the cached value; the value, which is the value stored in the cache; and the reason, which is a custom cache object containing the reason the item was removed. These can then be used to reconstruct the cache item if desired.
|
Private Sub CacheRemoved(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason) lnkMessage.Text = "Key " & key & " containing value " & value.ToString() & " was removed for reason " & reason.ToString() End Sub |
Next, the page unload method updates the cached item if needed. A Boolean variable states whether a change has been made to the textbox value, and updates the cache to reflect this change. How the update variable works is when a change is made and submitted for processing to the server (such as a link button to save the contents to the database or a textboxes text changed event is declared), the value is set to true in those instances. This works well with the web form lifecycle, because first the page loads, then the user control event is executed (button click, text changed), and lastly the unload method is executed.
|
'Boolean value to track updates Private m_blnUpdatesMade As Boolean = False Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload 'If updates made, insert the new value into the cache If (m_blnUpdatesMade) Then Cache.Insert("MyCachedItem", TextBox1.Text) End If End Sub |
This linkbutton's event handler removes the cached item from the cache, if the cached item exists. This is pretty straightforward and will remove the item from the cache before any expiration takes place.
|
Private Sub lnkRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkRemove.Click 'If cached item exists If (Not IsNothing(Cache("MyCachedItem"))) Then 'Remove the cached item Cache.Remove("MyCachedItem") End If End Sub |
This is a simple example of caching and illustrates the syntax involved with utilizing the basic commands. See the downloadable code for a more involved example.
About the Code
The code attached is an ASP.NET project. Please copy the folder to your wwwroot directory in order to use this example. Additionally, you may have to set this project up as an application for the virtual directory. In IIS, right-click the Caching virtual directory, select Properties. Where it says "Application Name", the button next to it should say "Remove". If it doesn't, hit the create button to create the application.
The example is a more complex example of Caching and how it would be used in a web site. The example is a ticket ordering system, where you enter the information into the web site, and the information is cached and shared among multiple web pages. The mechanism used to house the information will be a custom class, which in a realistic setting, could be altered to retrieve information from a database if needed.
The following pages are used in the web site:
The code for these pages is well documented, and is a simple, yet more involved, example of caching.
You may download the code here.