each user free memory on that server for the temporary storage of objects (strings,
integers, or any other kinds of objects).
The process of reading and writing data into session state is very similar to the
way we read and write data to the application state: instead of using the
Application object, we use the Session object. However, the Session object
doesn’t support locking and unlocking like the Application object does.
To test session state, you could simply edit the Page_Load method to use Session
instead of Application, and remove the Lock and UnLock calls if you added
them. The easiest way to replace Application with Session is by selecting Edit
> Find and Replace > Quick Replace.
In the page hit counter example that we created earlier in this chapter, we stored
the count in the application state, which created a single hit count that was shared
by all users of the site. Now, if you load the page in multiple browsers, you’ll see
that each increments its counter independently of the others.
Like objects stored in application state, session state objects linger on the server
even after the user leaves the page that created them. However, unlike application
variables, session variables disappear after a certain period of user inactivity.
Since web browsers don’t notify web servers when a user leaves a web site,
ASP.NET can only assume that a user has left your site after a period in which
it hasn’t received any page requests from that user. By default, a user’s session
will expire after 20 minutes of inactivity. We can change this timeframe simply
by increasing or decreasing the Timeout property of the Session object, as follows:
Visual Basic
Session.Timeout = 1560
You can do this anywhere in your code, but the most common place to set the
Timeout property is in the Global.asax file. If you open Global.asax, you’ll
see that it contains an event handler named Session_Start. This method runs
before the first request from each user’s visit to your site is processed, and gives
you the opportunity to initialize their session variables before the code in your
web form has a chance to access them.
Here’s a Session_Start that sets the Timeout property to 15 minutes:
Visual Basic File: Global.asax (excerpt)
Sub Session_Start(sender As Object, e As EventArgs)
Session.Timeout = 1560
End Sub
181
Working with User Sessions