What is the difference between Session.Abandon() and Session.Clear()
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.
HttpSessionState.Abandon Method
Cancels the current session.
Remarks
Once the Abandon method is called, the current session is no longer valid and a new session can be started. Abandon causes the End event to be raised. A new Start event will be raised on the next request.
Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId
attribute of the sessionState configuration element to true
. For more information, see Session Identifiers.
The End event is supported only when the Mode property is set to InProc.
sessionState Element (ASP.NET Settings Schema)
<sessionState mode="[Off|InProc|StateServer|SQLServer|Custom]" timeout="number of minutes" cookieName="session identifier cookie name" cookieless= "[true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile]" regenerateExpiredSessionId="[True|False]" sessionIDManagerType="session manager type" sqlConnectionString="sql connection string" sqlCommandTimeout="number of seconds" allowCustomSqlDatabase="[True|False]" useHostingIdentity="[True|False]" stateConnectionString="tcpip=server:port" stateNetworkTimeout="number of seconds" customProvider="custom provider name" compressionEnabled="[True|False]" sqlConnectionRetryInterval="number of seconds"> <providers>...</providers> </sessionState>