Examining the session duration and session events

Posted Mon, Jan 16 2006 16:39 by vapordan@hotmail.com

 

Article ID : 555082
Last Review : April 13, 2004
Revision : 1.0

Abstract

Session and its events are sometimes peculiar at best and down right complex at worst. The complexity stems from the need to service different state providers in the same architecture. This discussion examines some of the underlying reasons why session end and session start events don’t always seem to fire as a couple. The glue which holds the matrix together is an often overlooked participant called session id. Here is how the session id plays a pivotal role in this new world. A session start event fires for each new request. But, session end event fires based on the state of the session id and not necessarily on the termination of each request. This is interesting because it implies that a session end event does not necessarily follow a session start event. This behavior is often the cause of much confusion relating to the session end events. 
 
 

How does session abandon work?

The abandon method will destroy the session by sending a new session id cookie with an old expiration date. Then, abandon destroys the dictionary associated with the session. Whether session end event fires next is entirely dependent on the session id. It bears repeating: If the session id is regenerated, session end event fires. If the session id is not regenerated, session end fails to fire. So in one case, calling session abandon will invoke the session end event. And in another case, calling session abandon does not cause the session end event to fire. If the session id is being re-used then this session id is kept until the browser is closed even though a new page is requested. As long as the conditions are satisfied, the session id remains. Here is the complete test case example to force session end to fire.
 
private void Page_Load(object sender, System.EventArgs e)
{
Session["test"] = "test";
}
 
private void Button1_Click(object sender, System.EventArgs e)
{
Session.Abandon();
}
 
When the Button1_Click event fires off due to the user clicking a button on the form,
1 At least one request has completed successfully. This is the page_load routine executing successfully.
2 The session dictionary has been written to at least once. This is the page_load routine executing the single line of code.
 
We've looked at the session song and dance in enough detail to allow you to understand when these events fire. The song and dance is based on a set of rules. Once these rules are applied, the expected behavior is achieved. Failure to understand the rules leads to confusion and ill-behaved code.