How to use Cache in Class files?

This code shows how to use cache in a class file

// Removing data from cache

// Storing data into cache
System.Web.HttpContext.Current.Cache["Mydata"] = MyObject; // this can be a string, or any object

// Getting data from cache
object obj = System.Web.HttpContext.Current.Cache["Mydata"];


Author: Shuby Arora08 Feb 2009 Member Level: Gold   Points : 2

Cache: Its nothing but a thought kind of memory. In respect to it’s the memory of the machine/server from where the source-code is running. It is the one way which allow to store complex data for reusability.
Now think a criteria where clients access an ASP.NET page, there are basically two ways to provide them with the information they need:
• The ASP.NET page can either obtain information from server resources, such as from data that has been persisted to a database, or
• The ASP.NET page can obtain information from within the application.
Retrieving information from a resource outside the application will require more processing steps, and will therefore require more time and resources on the server than if the information can be obtained from within the application space.
Now, suppose the information’s which sent to browser’s have already been prepared then how faster the process of web-page.
The ASP.NET 3.5 Framework supports the following types of caching:
Page Output Caching
Page Output Caching caches an entire page.
Partial Page Caching
Partial Page Caching enables you to get around this problem by enabling you to cache only particular regions of a page.
DataSource Caching
You use DataSource Caching with the different ASP.NET DataSource controls such as the SqlDataSource and ObjectDataSource controls. When you enable caching with a DataSource control, the DataSource control caches the data that it represents.

Data Caching
Finally, Data Caching is the fundamental caching mechanism. Behind the scenes, all the other types of caching use Data Caching. You can use Data Caching to cache arbitrary objects in memory. For example, you can use Data Caching to cache a DataSet across multiple pages in a web application.

Try to use following:

public void AddItemToCache(Object sender, EventArgs e)
itemRemoved = false;
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (Cache["Key1"] == null)
Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60),TimeSpan.Zero, CacheItemPriority.High, onRemove);

public void RemoveItemFromCache(Object sender, EventArgs e)
if(Cache["Key1"] != null)

Author: Sasikumar18 Feb 2009 Member Level: Gold   Points : 1

Nice code

Compileable Code....

Good One........

Keep It UP..

post more for viewers

Thanks and regards

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: