In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Lance Fisher picture Lance Fisher · Dec 7, 2008 · Viewed 111.9k times · Source

Both Session.Clear() and Session.Abandon() get rid of session variables. As I understand it, Abandon() ends the current session, and causes a new session to be created thus causing the End and Start events to fire.

It seems preferable to call Abandon() in most cases, such as logging a user out. Are there scenarios where I'd use Clear() instead? Is there much of a performance difference?

Answer

splattne picture splattne · Dec 7, 2008

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.