Click here to Skip to main content
Click here to Skip to main content

Improve performace with Sessions using Cache

, 20 Jul 2005
Rate this:
Please Sign up or sign in to vote.
I wrote this short article to improve your ASP.NET application Sessions using Cache.


This is a very short article to help people who use SQL Sessions. As everybody knows, storing Sessions on your SQL Server is a great idea, however is also a performance nightmare. If you are using Sessions as much as I do, your SQL Server is just a little too busy retrieving Sessions here and there. So let me show you what I do in order to avoid round trips to SQL Server and use a little bit more the memory cache.

Sessions InProc vs. In Cache

I prefer to use the memory cache as much as I can as it is faster than going to the SQL Server every time I need a piece of information. Now I am sure you are thinking, just use Sessions InProc. Well, I am trying to avoid that as much as I can. Why? If you have used InProc, you can answer this question in a sentence. If you want to store Sessions on your SQL Server there is a reason for that (Web Farms or Web Gardens).

Cache does not work with Web Farms

I know! However if used with SQL Server, it makes it a little bit more interesting and fast. To retrieve the Session we will first check if there is a copy on the local cache, if not we will have to go to the SQL Server.

Let's write Code!

using System;
//Normally this is how we store and retrieve sessions
Session["Test"] = "Storing a string";
//Retrieving a string
string sTemp = Session["Test"];

So now let's do it with Cache:

AlsUtils.BetterSession pSession = new BetterSession();

// Store 2 keys
pSession["test"] = "hello";
pSession["bye"] = "Good Bye";

// Retrive them
string sTemp = pSession["test"];
string sTemp2 = pSession["bye"];

//Clear the cache at logout

The simple class that makes everything possible:

using System;
using System.Collections;

namespace AlsUtils
    /// <SUMMARY>
    /// Summary description for BetterSession.
    /// </SUMMARY>    
    public class BetterSession : DictionaryBase
        public object this[string key]
                if (System.Web.HttpContext.Current.Cache[
                    System.Web.HttpContext.Current.Session.SessionID + 
                    "~" + key] != null )
                         + "~" + key]);
                else if (System.Web.HttpContext.Current.Session[key] != null )
                           + "~" + key] = 
                        + "~" + key, System.Web.HttpContext.Current.Cache[
                        + "~" + key]);

                return (null);

                  + "~" + key] = value;
                System.Web.HttpContext.Current.Session[key] = value;
                                                + "~" + key, value);
        public void ClearSession()
            string sSessionID = 

            ArrayList pArray = new ArrayList(Keys);

            for ( int i=0; i<pArray.Count; i++)
                if ( pArray[i].ToString().IndexOf(sSessionID+"~") == 0)


        //add a string based on key
        protected void Add(string key, object oValue) 
            this.Dictionary.Add(key, oValue); 
        //see if collection contains an entry corresponding to key
        protected bool Contains(string key)
            return this.Dictionary.Contains(key);

        //we will get to this later
        protected ICollection Keys
            get {return this.Dictionary.Keys;}



Well this is the idea. There is something pretty important to remember, the cache does not have time limit, so if you want the Cache to destroy itself in 30 minutes, you'll have to change the line that adds that to:

  value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, 

If your application sets all the Sessions in the beginning and then you use Session to read the configuration for that user, this simple class will save you lots of round trips to the SQL Session database.

Hope this helps some people.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Albert Pascual
Web Developer
United States United States
Al is just another Software Engineer working in C++, ASp.NET and C#. Enjoys snowboarding in Big Bear, and wait patiently for his daughters to be old enough to write code and snowboard.
Al is a Microsoft ASP.NET MVP

Comments and Discussions

GeneralCache Timeout Pinmembermay21525-Jan-07 0:56 
GeneralHttpContext issues PinmemberMorten on GIS15-Dec-05 11:58 
GeneralRe: HttpContext issues Pinmembercaliff2218-Jun-12 12:49 
General*Very* dangerous in web farms - Use ASP.NET Session State Service instead! Pinmemberaxelriet20-Jul-05 23:05 
GeneralDangerous in web-farms PinmemberMarc Brooks20-Jul-05 14:49 
GeneralRe: Dangerous in web-farms PinmemberAlbert Pascual20-Jul-05 14:51 
GeneralRe: Dangerous in web-farms PinmemberMarc Brooks20-Jul-05 15:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150302.1 | Last Updated 20 Jul 2005
Article Copyright 2005 by Albert Pascual
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid