What is the difference between Session.Abandon() and Session.Clear()
When you Abandon()
a Session, you (or rather the user) will get a new SessionId (on the next request).
When you Clear()
a Session, all stored values are removed, but the SessionId stays intact.
This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...
Session.Clear()
will CLEAR the values of all the keys but will NOT cause the session end event to fire.
Session.Abandon()
will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.
So, in my case (and perhaps in yours?), I needed Clear()
followed by Abandon()
.
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:
- Abandon raises Session_End request.
- Clear removes items immidiately, Abandon does not.
- 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.