Asp.net Cache Object

Asp.net Cache Object

Asp.net cache object

Here we will see how to cache and consume data stored inside cache object. Data stored in cache can be expired by time span. Once application pool get recycled all cache objects becomes empty or null.

Remember: Cache objects are in process memory instances. In web gardening scenario you can have multiple worker processes. For each worker process there is new copy of same cache objects. Let’s say you have 5 worker process and you created one cache object of size 1MB. Total number of cache object in application pool would be 5 and total number of space consumed would be 5MB.

In below example we will have list of dates. we will store this list inside a cache for 20 second. After 20sec data would be expired.

List<DateTime> GetDates()
{
  List<DateTime> lu = new List<DateTime>();
   lu.Add(DateTime.Now);
   lu.Add(DateTime.Now);
   lu.Add(DateTime.Now);
   lu.Add(DateTime.Now);
   return lu;    
}

Let’s see how to store list of dates inside a cache object cache[“Dates”].

public List<DateTime> ListOfDatesFromCache
  {
     get
     {
         if(Cache["Dates"]!= null)
         {
         
         List<DateTime> ld = new List<DateTime>();
         ld = (List<DateTime>)Cache["Dates"];
         
          return  ld;
         }
         else
         {

           List<DateTime> ld = new List<DateTime>();
                          Cache.Add("Dates", 
                            GetDates(), 
                            null, 
                            System.Web.Caching.Cache.NoAbsoluteExpiration, 
                            new TimeSpan(0,0,20), 
                            System.Web.Caching.CacheItemPriority.Default,
                            null);
             ld = (List<DateTime>)Cache["Dates"];
             
             return ld;
         }
         
     }

You can see above we have created a property which returns list. If cache object is null, we are calling GetDates() function and load it inside a cache for 20 second. Whenever program tries to access ListOfDatesFromCache it will return list of dates.

In real life scenarios you can call the data base and store the data inside cache. It is useful when you don’t want to validate each request generated by user against database.

Cache object example in Asp.net.

using System;
using System.Web;
using System.Collections.Generic;
 

public partial class Demo : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
     
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
   
   foreach(DateTime dt in ListOfDatesFromCache) 
   {
      Response.Write(dt.ToString());
   }
   
  }
  
  List<DateTime> GetDates()
  {
    List<DateTime> lu = new List<DateTime>();
     lu.Add(DateTime.Now);
     lu.Add(DateTime.Now);
     lu.Add(DateTime.Now);
     lu.Add(DateTime.Now);
     return lu;    
  }

  public List<DateTime> ListOfDatesFromCache
  {
     get
     {
         if(Cache["Dates"]!= null)
         {
         
         List<DateTime> ld = new List<DateTime>();
         ld = (List<DateTime>)Cache["Dates"];
         
          return  ld;
         }
         else
         {

           List<DateTime> ld = new List<DateTime>();
                          Cache.Add("Dates", 
                            GetDates(), 
                            null, 
                            System.Web.Caching.Cache.NoAbsoluteExpiration, 
                            new TimeSpan(0,0,20), 
                            System.Web.Caching.CacheItemPriority.Default,
                            null);
             ld = (List<DateTime>)Cache["Dates"];
             
             return ld;
         }
         
     }
  }
}

VB.net example to store data in Cache.

Imports System.Web
Imports System.Collections.Generic


Public Partial Class Demo
	Inherits System.Web.UI.Page
	Protected Sub Page_Load(sender As Object, e As EventArgs)

	End Sub
	Protected Sub Button1_Click(sender As Object, e As EventArgs)

		For Each dt As DateTime In ListOfDatesFromCache
			Response.Write(dt.ToString())
		Next

	End Sub

	Private Function GetDates() As List(Of DateTime)
		Dim lu As New List(Of DateTime)()
		lu.Add(DateTime.Now)
		lu.Add(DateTime.Now)
		lu.Add(DateTime.Now)
		lu.Add(DateTime.Now)
		Return lu
	End Function

	Public ReadOnly Property ListOfDatesFromCache() As List(Of DateTime)
		Get
			If Cache("Dates") IsNot Nothing Then

				Dim ld As New List(Of DateTime)()
				ld = DirectCast(Cache("Dates"), List(Of DateTime))

				Return ld
			Else

				Dim ld As New List(Of DateTime)()
				Cache.Add("Dates", GetDates(), Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, New TimeSpan(0, 0, 20), System.Web.Caching.CacheItemPriority.[Default], _
					Nothing)
				ld = DirectCast(Cache("Dates"), List(Of DateTime))

				Return ld

			End If
		End Get
	End Property
End Class

The last parameter of cache add method is null. You can add call back reference instead of null. It will get called when cache objects get expired.

Tags:

cache object nullasp net image uploadAsp.net Interview Questions for 2 years or 3 years experianceSessions In AspnetASp.net 2.0 step by step Membership Provider ASP.net File HandlingAsp.net Convert String To ImageAsp.net How To Write a Cookie and ReadHow are you using session variables in Asp.net with C#.netWhat is web garden in Asp.net?ASP net Write Text On Image C#.net and Vb.net program

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.