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

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.

Method 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()?

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x