Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with Application caching in ASP.Net

Caching is a process by which some data is stored in memory for frequent usage. This helps to improve performance of your application.

Caching is the process of storing data, pages or parts of a web page in memory so that they can be retrieved faster than they could be accessed from a file or a database. This helps to improve performance and increase the scalability of a web application. For example, if you have an e-commerce website with a product catalogue, you can cache a huge part of the catalogue. Data that changes infrequently but is accessed by a lot of users is a good example of what you can cache. The first request to the data stores it in the cache and subsequent requests are served from the cache until the cache expires.

ASP.Net allows you to take advantage of caching without writing too much code to deal with associated complexities like cache expiration, updates to data etc. There are two types of caching

  • Application caching - represents a collection that can store any object in memory
  • Page output caching - where a page or part of a page is stored in memory

This lesson deals with application caching.

Application caching

Application caching, also called application data caching, refers to storing data in cache. The cache is available as a page property. It represents a collection class of the type System.Web.Caching.Cache. The Page.Cache property uses an application wide cache which means that the data can be shared between user requests and sessions.

Using Cache object

Items can be assigned to cache by giving then a name (key) and assigning a value. Items can be retrieved from cache by checking for the key.

Listing 1: Using cache object

//Assign an item to cache
Cache[“Greeting”]=”Hello world”;

//Retrieve an item from cache
If (Cache[“Greeting”] != null)
{
LabelCache.Text=(string)Cache[“Greeting”];
}

It is always a good practice to check whether the cache item is null or not. There is a possibility that the item has expired. If not retrieve it from the original source and place it into the cache again if required. You must also remember to cast the cache item back to the correct type.

You normally wouldn’t cache a string. More expensive items like a database query result or a file are more likely to be placed into cache in web applications. You can cache any object types, including custom types as long as they are serializable.

Inserting items into cache

The above example shows how to add an item to cache in the simplest way. There is also an Insert method available for the cache object which allows better controls for the programmers. With this method you can control the dependencies of the item and the cache expiry.

Let us have a look at the various parameters

Key - This is the name used to access the item. The key must be unique in cache.

Value - Data (as an object) that you want to cache

Dependencies - A CacheDependency object which specifies a file or a key to another item in the cache. When the file or the key changes the cache item is removed automatically. If you cache a file you must configure a dependency for the file so that when the file changes the cache item is removed automatically. You can also call the onRemoveCallBack parameter to reload the cached item.

absoluteExpiration - Time as a datetime object at the which the object should be removed from cache. This is an absolute value and does not take into consideration whether the cache item has been accessed recently by a user. The parameter can be set to Cache.NoAbsoluteExpiration if you do not wish to use this.

slidingExpiration - Time as a timespan object which specifies that the object should be removed from cache after this timespan if it has not been accessed by the user. The parameter can be set to Cache.NoSlidingExpiration if you do not wish to use this.

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 items are removed first. The values for priority from lowest (most likely to be removed) to highest (least likely to be removed) are

  • Low
  • BelowNormal
  • Normal - This is the default value
  • AboveNormal
  • High
  • NotRemovable

onRemoveCallBack - A delegate that is called when an item is removed from cache. This can be null if you do not wish to use it.

Defining a cache dependency

A cache dependency links a cached item to something else such as a file or another item in cache. ASP.Net monitors the dependency and invalidates the cache when the dependent item changes.

Listing 2: Defining cache dependency

Cache.Insert("filetext", System.IO.File.ReadAllText(Server.MapPath("caching.txt")), new
CacheDependency(Server.MapPath("caching.txt")), DateTime.Now.AddMinutes(2),
Cache.NoSlidingExpiration);

The above code shows how to a cache item is dependent on a file “caching.txt”. The dependency is specified as new CacheDependency(Server.MapPath("caching.txt"))

Defining an absolute expiration

This parameter sets a datetime at which the cache item expires. The code above listing specifies a datetime object which is 2 minutes away in the future as the cache item absolute expiry.

Defining a sliding expiration

A sliding expiration indicates the amount of time (timespan object) that must elapse between subsequent requests before an item must be removed from the cache. Each time a request is made the slider restarts.

The below code listing specifies a timespan object which is 10 minutes away in the future as the cache item sliding expiry.

Listing 3: Defining sliding expiration

Cache.Insert("filetext", System.IO.File.ReadAllText(Server.MapPath("caching.txt")), new
CacheDependency(Server.MapPath("caching.txt")), Cache.NoAbsoluteExpiration, new
TimeSpan(0,10,0));

With the sliding expiration it is possible that heavy usage will result in an item never being removed from the cache. This can prevent any updates from showing through. So it is better to provide an absolute expiration together with the sliding expiration.

It is also a good idea to provide dependencies in case of an absolute or sliding expiration is specified so that the updates to item show through.

Hope this article was useful! Thanks



I am a Senior Web Developer from London with over 5years of experience in ASP.NET, HTML, CSS. I am well versed in VB.Net, C# and SQL as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login