17 August, 2011

Application Caching in Asp.net

Application Caching (also called application data caching) is the process of storing data (not
pages) in a cache object. The cache object is available as a property of the Page object. It
represents a collection class of type System.Web.Caching.Cache. The Page.Cache property
actually uses an application-wide cache (not just a page-specific cache). This means that
a single Cache object exists for your entire application; items in the Cache can be shared
between user sessions and requests.

Using the Cache Object

You work with the Cache object as you would with Session or similar objects. You can assign
items directly to the cache by giving them a name (key) and assigning them an object (value).
You retrieve objects from the cache by checking for the key.
Always verify that an item is not null. If a value is null, that value either hasn’t been cached
or it has expired from the cache. If an item is null, you should retrieve it from the original source
and, in most cases, place it into the cache.

The following code sample demonstrates how to cache and retrieve a String object with
the Cache collection.

Sample of Visual Basic Code
Cache("Greeting") = "Hello, cache!"
If Cache("Greeting") IsNot Nothing Then
Label1.Text = DirectCast(Cache("Greeting"), String)
Else
Label1.Text = "Hello, world!"
End If

Sample of C# Code
Cache["Greeting"] = "Hello, cache!";
if (Cache["Greeting"] != null)
Label1.Text = (string)Cache["Greeting"];
else
Label1.Text = "Hello, world!";

You wouldn’t normally cache a static string in your application; you’d more likely cache a file,
a database query result, or other data that is shared and expensive to obtain. You can cache any
object type, including your own custom types as long as they are serializable. However, just
as you would from any generic collection, you must cast the object back to the correct type
when you access it from the cache.



Inserting Items into the Cache

The previous example demonstrates that you can use the Cache object as you would Session or
Application. You can access much more sophisticated functionality, however, by using the Insert
method to add an item to the cache and control how that item gets removed from the cache.
This functionality includes automatic removal based on a specific period of time, removal when
a file changes, or removal when another cache object expires.

Insert has a number of overloads based on the many parameters you can set when adding
an item to the cache.
 The following list outlines the parameters of the Cache.Insert method:

key  This is the name (as a String) that you’ll use to access the cached object in the
Cache collection. The key must be unique in the cache.
value This is the data (as an Object) that you want to cache.
dependencies  A CacheDependency object identifies a file or a key to another item in
the cache. When the file or related cached item is changed, this will trigger this cached
object to be removed from the cache.If you cache a file, you should configure a dependency for the file so that it is removed from the cache after being modified. This helps ensure that your cache never becomes
stale. You might also call the parameter onRemoveCallback to reload the cached item.
absoluteExpiration  This is the time (as a DateTime object) at which the object
should be removed from the cache. This is absolute and therefore does not take
into consideration whether the item has been recently accessed by a user. If you
do not wish to use absolute expiration, you can set this property to System.Web
.Caching.Cache.NoAbsoluteExpiration.
slidingExpiration  This is the time (as a TimeSpan object) after which the object
should be removed from the cache if it has not been accessed by a user. Set this to
System.Web.Caching.Cache.NoSlidingExpiration if you don’t want to use it.
priority  This is a CacheItemPriority enumeration value that you can use to determine
which objects are removed first when memory starts to run low (this process is called
scavenging). Lower priority objects are removed sooner. The values for priority, from
lowest (most likely to be removed) to highest (least likely to be removed) include the
following:
  1. Low
  2. BelowNormal
  3. Normal (Default is equivalent to Normal)
  4. AboveNormal
  5. High
  6. NotRemovable
onRemoveCallback This is an event handler that is called when the object is removed
from the cache. This can be null if you don’t want to specify a callback method.
(FOR MORE CLEAR VISION VISIT :-http://msdn.microsoft.com/en-us/library/05kd8d77.aspx)

Defining a Cache Dependency


A cache dependency links a cached item to something else such as a file or another item in
the cache. ASP.NET monitors the dependency and invalidates the cache if the dependent
item changes. The following code sample demonstrates how to make a cache dependency
based on a file. If the file the cache is dependent upon changes, the object is removed
from the cache.

Sample of Visual Basic Code
Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"), _
New System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.txt")))

Sample of C# Code
Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"),
new System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.txt")));

You can also create multiple dependencies for a single cached item. The following
example demonstrates how to use an AggregateCacheDependency object to add an item
to the cache that is dependent on both an item named CacheItem1 and a file named
SourceFile.xml.

Sample of Visual Basic Code
Dim dep1 As CacheDependency = New CacheDependency(Server.MapPath("SourceFile.txt"))
Dim keyDependencies2 As String() = {"CacheItem1"}
Dim dep2 As CacheDependency = New System.Web.Caching.CacheDependency(Nothing, _
keyDependencies2)
Dim aggDep As AggregateCacheDependency = New System.Web.Caching.
AggregateCacheDependency()
aggDep.Add(dep1)
aggDep.Add(dep2)
Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"), aggDep)

Sample of C# Code
System.Web.Caching.CacheDependency dep1 =
new System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.txt"));
string[] keyDependencies2 = { "CacheItem1" };
System.Web.Caching.CacheDependency dep2 =
new System.Web.Caching.CacheDependency(null, keyDependencies2);
System.Web.Caching.AggregateCacheDependency aggDep =
new System.Web.Caching.AggregateCacheDependency();
aggDep.Add(dep1);
aggDep.Add(dep2);
Cache.Insert("FileCache", File.ReadAllText("SourceFile.txt"), aggDep);


Setting an Absolute Cache Expiration


To cache an object for a set amount of time, pass the absoluteExpiration parameter to the
Cache.Insert method. This parameter sets a time in the future at which your data should
expire. The DateTime.Now object has a variety of methods for adding a specific number
of minutes to the current time. The following example demonstrates this.

Sample of Visual Basic Code
Cache.Insert("FileCache", "CacheContents", Nothing, DateTime.Now.AddMinutes(10), _
Cache.NoSlidingExpiration)
Sample of C# Code
Cache.Insert("FileCache", "CacheContents", null, DateTime.Now.AddMinutes(10),
Cache.NoSlidingExpiration);

Setting a Sliding Cache Expiration


If you want your most frequently used cached objects to stay in your cache longer, you can
specify a sliding expiration. A sliding expiration indicates the amount of time that must elapse
between subsequent requests before an item is removed from the cache. Each time a new
request comes in for an item, the sliding scale restarts.
You set a sliding expiration by passing a TimeSpan to the slidingExpiration parameter
of the Insert method. The TimeSpan is the time after the last read request that the cached
object will be retained. This example shows you how to keep an object in cache for 10
minutes after the last request.


Sample of Visual Basic Code
Cache.Insert("CacheItem7", "Cached Item 7", _
Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, New TimeSpan(0, 10, 0))
Sample of C# Code
Cache.Insert("CacheItem7", "Cached Item 7",
null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));

Especially with a sliding cache expiration, it is possible that heavy usage will result in an
item never being removed from the cache, preventing updates to the original object from
being accessed. By defining an absolute expiration in addition to a sliding expiration, you
can be sure an object is eventually removed. When possible, add a cache dependency to
your absolute and sliding cache expirations to immediately remove the cached object
when the original is updated.



No comments:

Post a Comment