MVC optimization for Session.Clear(), Session.Abandon(), Session.RemoveAll()?

44,672

Solution 1

Session.Clear and Session.RemoveAll are identical; the latter just calls the former. They immediately remove all items stored in the session, but the session itself survives. Session_OnEnd does not fire.

Session.Abandon doesn't actually clear the values immediately, it just marks the session to be abandoned at the end of the current request. You can continue to read the values for the rest of the request. If you write to the session later in the request, the new value will be quietly discarded at the end of the request with no warning. Session_OnEnd fires at the end of the request, not when Abandon is called.

Solution 2

Session.Clear does not kill a Session, it clears all values. Session.Abandon actually kills the Session.

Looks like most of this is addressed here: In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Solution 3

Little late here but would like to share the proof that @stevemegson is correct as Session.RemoveAll internally calls Session.Clear

public void Clear()
        {
            this._container.Clear();
        }
        public void RemoveAll()
        {
            this.Clear();
        }

And so there is exactly no difference between at all

And session.Abandon calls

public void Abandon()
        {
            this._container.Abandon();
        }

which basically do :)..

public void Abandon()
{
    this._abandon = true;
}
Share:
44,672
MrM
Author by

MrM

Updated on February 26, 2020

Comments

  • MrM
    MrM about 4 years

    I am using a few sessions that should be terminated when the user is done. I stumbled on these 3 session killers. When is the best time to use these as I use sessions more time than not. Also, is there any other session termination I am not aware of?