Delete session state and add service data

The following describes how I usually process objects in the Session state, I have a constant string as the name of the session, and then a property with get and set to Object.

I was wondering if there was a call to "Session.Remove ()" (so that everything was clean and tidy), and if there was significant overhead and this deletion.

I have a Session.Remove there mainly 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 is not 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 in accordance with the answers below, I 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!

+3
source share
3

, IDisposable, , Dispose.

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

,

 Session[sesMyObject] = value

 Session.Remove(sesMyObject);        
 Session.Add(sesMyObject, value);
+2

. MSDN

name , .

+2
Session[sesMyObject] = value;

in short, it is easier to read and have slightly better performance, but if this code is not repeated many times in a row, it should not matter.

+1
source

Source: https://habr.com/ru/post/1702711/


All Articles