Monday, March 28, 2011

Session State removing and adding overhead

The following is how I usually handle objects in Session State, I have a const string as the session name and then have a property with a get and set for the Object.

What I was wondering was if the 'Session.Remove()' call was necessary (to keep things clean and tidy) and if there was significant overhead and doing this removal.

I have the Session.Remove there basically because it makes me feel better (OCD i know), and makes me feel like the session is cleaner, but I would like to know if it isn't needed.

private const string sesMyObject = "{C2CC72C3-1466-42D4-8579-CAA11F261D55}";
public MyObject MyObjectProperty
{
    get
    {
        return Session[sesMyObject] as MyObject;
    }
    set
    {
        Session.Remove(sesMyObject);
        Session.Add(sesMyObject, value);
    }
}

EDIT per the answers below i have changed my properties to the following:

private const string sesMyObject = "{C2CC72C3-1466-42D4-8579-CAA11F261D55}";
public MyObject MyObjectProperty
{
    get
    {
        return Session[sesMyObject] as MyObject;
    }
    set
    {
        Session[sesMyObject] = value;
    }
}

thanks!

From stackoverflow
  • If you really want to be safe, try converting the object to a IDisposable, and if it succeeds, call Dispose.

    IDisposable sesDispObj =  Session[sesMyObject] as IDisposable;
    if (sesDispObj != null)
       sesDispObj.Dispose();
    

    Other than that,

     Session[sesMyObject] = value
    

    is pretty much the same as

     Session.Remove(sesMyObject);        
     Session.Add(sesMyObject, value);
    
  • It's overkill. Refering MSDN

    If the name parameter refers to an existing session state item, the existing item is overwritten with the specified value.

  • Session[sesMyObject] = value;
    

    is shorter, simpler to read, and should have slightly better performance, but unless this code is being repeated very many times in succession, it shouldn't make a difference.

0 comments:

Post a Comment