Difference between ASP.NET Sessions, Application variables and Cache objects.



When developers start with ASP.NET Web Forms the question I always get is; where is the best place to store user information, the application variable, the session state, cookies, database or the cache objects?

This is not an easy answer there are so many variables and options. In a nutshell Session state can make a big difference depending there that session state is also stored, depending on so many factors, how many servers you going to need? how many users you need to support?

Please find the code below to test for yourself how Session, Application and Cache variables work.

In the previous post, you can see how Cache has a callback when the object gets remove from memory.

The difference from an Application variable and Cache is mainly that you can assign the time the Cache variable will be stored in memory.

The main difference between Cache, Application and Sessions is the later is isolated by user, so every user has their own pool of Session variables to use, Session variable gets destroyed after Session timeout.

   1: public class MyCacheInfo
   2:         {
   3:             public string Url
   4:             {
   5:                 get;
   6:                 set;
   7:             }
   8:             public object MyValue
   9:             {
  10:                 get;
  11:                 set;
  12:             }
  13:         }
  14:  
  15:  
  16:         static string _myObject = "MyObject";
  17:         static CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(RemoveCallback);
  18:  
  19:         public static void RemoveCallback(string k, Object v, CacheItemRemovedReason r)
  20:         {
  21:             MyCacheInfo info = v as MyCacheInfo;
  22:  
  23:             WebClient net = new WebClient();
  24:             net.DownloadData(info.Url.Replace("?Al=1","") + "?Al=1");
  25:            
  26:         }
  27:  
  28:         protected void Page_Load(object sender, EventArgs e)
  29:         {
  30:             if (Request.Params["Al"] != null)
  31:             {
  32:                 DateTime dtExpiration = DateTime.UtcNow.AddSeconds(10);
  33:  
  34:                 MyCacheInfo info = new MyCacheInfo()
  35:                 {
  36:                     MyValue = DateTime.Now,
  37:                     Url = HttpContext.Current.Request.Url.OriginalString
  38:                 };
  39:                 Cache.Add(_myObject,
  40:                       info,
  41:                       null,
  42:                       dtExpiration,
  43:                       System.Web.Caching.Cache.NoSlidingExpiration,
  44:                       System.Web.Caching.CacheItemPriority.High,
  45:                       onRemove);
  46:             }
  47:         }
  48:  
  49:         
  50:         protected void Button1_Click(object sender, EventArgs e)
  51:         {
  52:             // Add everything here
  53:             Session[_myObject] = TextBoxSession.Text;
  54:             Application[_myObject] = TextBoxApplication.Text;
  55:  
  56:  
  57:             MyCacheInfo info = new MyCacheInfo()
  58:             {
  59:                 MyValue = TextBoxCache.Text,
  60:                 Url = HttpContext.Current.Request.Url.OriginalString
  61:             };
  62:  
  63:             DateTime dtExpiration = DateTime.UtcNow.AddSeconds(10);
  64:             Cache.Add(_myObject,
  65:                        TextBoxCache.Text,
  66:                        null,
  67:                        dtExpiration,
  68:                        System.Web.Caching.Cache.NoSlidingExpiration,
  69:                        System.Web.Caching.CacheItemPriority.High,
  70:                        onRemove);
  71:            
  72:         }
  73:  
  74:  
  75:  
  76:         protected void Button2_Click(object sender, EventArgs e)
  77:         {
  78:             //Retrive
  79:             if (Session[_myObject] != null)
  80:                 LabelSession.Text = Session[_myObject].ToString();
  81:             else
  82:                 LabelSession.Text = "No Session";
  83:  
  84:             if (Application[_myObject] != null)
  85:                 LabelApplication.Text = Application[_myObject].ToString();
  86:             else
  87:                 LabelApplication.Text = "No Application";
  88:  
  89:             if (Cache[_myObject] != null)
  90:                 LabelCache.Text = Cache[_myObject].ToString();
  91:             else
  92:                 LabelCache.Text = "No Cache";
  93:         }
  94:  
  95:     }
Hope this helps

Cheers

Al

Published Monday, March 01, 2010 7:51 PM by albertpascual
Filed under:

Comments

# Dew Drop – March 2, 2010 | Alvin Ashcraft's Morning Dew

Tuesday, March 02, 2010 10:03 AM by Dew Drop – March 2, 2010 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop – March 2, 2010 | Alvin Ashcraft's Morning Dew

# Die neuen Frisurentrends f??r das Fr??hjahr

Thursday, March 25, 2010 8:32 PM by Die neuen Frisurentrends f??r das Fr??hjahr

Pingback from  Die neuen Frisurentrends f??r das Fr??hjahr

# Application Variable Asp.net | More More Pics

Saturday, February 19, 2011 8:04 AM by Application Variable Asp.net | More More Pics

Pingback from  Application Variable Asp.net | More More Pics

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Wednesday, August 10, 2011 6:03 PM by Ana

muchas gracias!!! despues de dos dias buscando, al fin alquien que explica en una forma tan simple la forma de capturar variables para novatos como yo.

:)

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Monday, August 27, 2012 3:08 PM by Eva

This blog is totally aowmese!!Actually i love it so much,that i just would like to make a fast proposal for everybody visiting it.You know 100 % that in the world of Internet Marketing,everyone wants quick results,wants to make some fast bucks and basically wants dream life,but often the key element is not there and it is one word- SEO.Without proper promotional strategy,your dreams are gone,your flat stays the same and no one will even know,that you have online presence.So do yourself a favour and click my name.Yeah,it is that easy and i guarantee,that you will get results even for $5!!!

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Wednesday, August 29, 2012 11:34 PM by Sanjeev

I in addition to my pals have been exniiamng the best ideas on your website and all of the sudden developed a terrible suspicion I never thanked the site owner for them. My young boys had been consequently joyful to study all of them and have now clearly been taking pleasure in those things. I appreciate you for really being indeed helpful and for pick out certain nice subjects most people are really eager to learn about. Our own honest apologies for not expressing appreciation to you earlier.Read more on my blog .

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Thursday, November 08, 2012 4:48 AM by YrbkeIFYpLsmYYNWVe

nJYzd3 Very neat blog.Really looking forward to read more. Really Cool.

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Tuesday, December 18, 2012 10:27 AM by phelkzbcgbz@gmail.com

US science agency Noaa to deliver annual report on polar region after year of record-breaking and extreme weather events

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Thursday, January 24, 2013 1:19 AM by Auto Parts Center

Auto Parts Center - Winnipeg - phone number & address - MB - Auto Part Manufacturers & Wholesalers, Car Racing & Sport Parts & Accessories

# re: Difference between ASP.NET Sessions, Application variables and Cache objects.

Thursday, January 31, 2013 12:54 PM by bdrZGsEYKAYEaqWro

JkMxwk Im obliged for the blog article.Thanks Again. Much obliged.

Leave a Comment

(required) 
(required) 
(optional)
(required)