Click here to Skip to main content
15,886,067 members
Articles / Web Development / ASP.NET
Article

Improve performace with Sessions using Cache

Rate me:
Please Sign up or sign in to vote.
3.64/5 (7 votes)
20 Jul 20052 min read 90.9K   514   47   7
I wrote this short article to improve your ASP.NET application Sessions using Cache.

Introduction

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!

C#
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:

C#
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
pSession.ClearSession();

The simple class that makes everything possible:

C#
using System;
using System.Collections;

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

                return (null);
            }

            set 
            { 
                System.Web.HttpContext.Current.Cache[
                  System.Web.HttpContext.Current.Session.SessionID 
                  + "~" + key] = value;
                System.Web.HttpContext.Current.Session[key] = value;
                Add(System.Web.HttpContext.Current.Session.SessionID 
                                                + "~" + key, value);
            } 
        }
        
        public void ClearSession()
        {
            string sSessionID = 
              System.Web.HttpContext.Current.Session.SessionID;

            ArrayList pArray = new ArrayList(Keys);

            for ( int i=0; i<pArray.Count; i++)
            {
                if ( pArray[i].ToString().IndexOf(sSessionID+"~") == 0)
                    System.Web.HttpContext.Current.Cache.Remove(
                                          pArray[i].ToString());

            }
        }

        //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;}
        }

    }
}

Conclusion

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:

C#
System.Web.HttpContext.Current.Cache.Insert(sSessionID+"~"+key, 
  value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, 
  TimeSpan.FromMinutes(30));

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.

License

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


Written By
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

Blog

Comments and Discussions

 
GeneralCache Timeout Pin
may21524-Jan-07 23:56
may21524-Jan-07 23:56 
GeneralHttpContext issues Pin
Morten on GIS15-Dec-05 10:58
Morten on GIS15-Dec-05 10:58 
GeneralRe: HttpContext issues Pin
califf2218-Jun-12 11:49
califf2218-Jun-12 11:49 
General*Very* dangerous in web farms - Use ASP.NET Session State Service instead! Pin
Axel Rietschin20-Jul-05 22:05
professionalAxel Rietschin20-Jul-05 22:05 
GeneralDangerous in web-farms Pin
Marc Brooks20-Jul-05 13:49
Marc Brooks20-Jul-05 13:49 
GeneralRe: Dangerous in web-farms Pin
Albert Pascual20-Jul-05 13:51
sitebuilderAlbert Pascual20-Jul-05 13:51 
GeneralRe: Dangerous in web-farms Pin
Marc Brooks20-Jul-05 14:24
Marc Brooks20-Jul-05 14:24 

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

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