What is the difference between Session.Abandon() and Session.Clear()?

I found this post on Stack Overflow.

If you are not familiar with SO or it other domains, I would suggest visiting the site. Even if you are not a programmer, there are many other sites associated with it that I’m sure you can find interest in. Check the bottom of the page if you cannot find the sister websites.

Anyhow, back to the question.

I had an issue where session was causing me problems on return visits and the cookies being saved from the previous visit. I needed to clear it and start fresh. I tried the Session.Abandon() but that made things worse as it kept logging me out as soon as I tried to log back in. It seems that session was flagged as Session End even if I rebuilt the session and the user could not log back on.

Here is the answer that seemed to explain it the best to me:

Clear – Removes all keys and values from the session-state collection.

Abandon – removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out.
It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.

You say:

When I test Session, it doesn’t makes any change when I Abandon the session.

This is correct while you are doing it within one request only.
On the next request the session will be different. But the session ID can be reused so that the id will remain the same.

If you will use Session.Clear you will have the same session in many requests.

Generally, in most cases you need to use Session.Clear.
You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  1. Abandon raises Session_End request.
  2. Clear removes items immidiately, Abandon does not.
  3. Abandon releases the SessionState object and its items so it can ba garbage collected to free the resources. Clear keeps SessionState and resources associated with it.

Hope it helps, as usual, this is just for reference for me.

Share

Be the first to comment

Leave a Reply