Wednesday, August 18, 2010

Best way to end ASP.NET session

There are mainly three methods in Session object which serve similar purpose.

1. Session.Clear(): This will immediately remove all objects stored inside Session object. Session object basically stores a collection of key(string) vs value(object). After calling this, you will find Session.count equals to zero but Session object itself will still be alive and you can again add new key/value items to it.

2. Session.RemoveAll(): It behaves exactly the same way as Session.Clear. It just wraps Session.RemoveAt at one shot. You can specify index in Session.RemoveAt to remove items one by one. You can also call Session.Remove and pass key to remove that key/value pair item. It could be slower than Session.Clear which essentially is made just to clear all the items.

3. Session.Abandon(): If you have used Session.Clear or Session.RemoveAll, though you have got rid of any and all objects stored in session but session object itself remains alive and could be used further. Session.Abandon just cancels the current session and session object gets destroyed.
The only point to remember here is that if you have used Session.Abandon, it will just mark the session to be destroyed but nothing will happen to session object for that request. As soon as the current request gets completed, session object will be canceled. So don't get surprised if nothing looks to happening to session object just after calling the abandon method, in the next request, you will find that session object to be destroyed and a new one to be created.

No comments:

Post a Comment