Quantcast

ASP.NET: Remove Unused Objects From the Session

Get the WebProNews Newsletter:
[ Business]

The Session in ASP.NET is a very simple way of storing user specific data for the duration of a single user session.

I’ve many times added data to the Session that had an even shorter lifespan. That could be as a data store for properties on AJAX enabled web pages and those properties don’t belong in the session after the visitor navigates to another page on my website.

To clean up, I would then delete those session objects that no longer is in use.

There are two way of deleting individual objects from the Session. You can set it to null or remove it.

Session["key"] = null;

or

Session.Remove("key");

I used to think that the Session would treat the two ways the same, but that is not the case. If you set the object to null, the key still exists in the Session even though the value is null.

This behaviour is the same as any other dictionary type classes in the CLR, but for some reason I thought that the Session was different.

That’s probably because you can ask if an key is present in the session without it throws an exception like many collection and dictionary type classes do if it isn’t. It’s because the Session is based on a HashTable.

After .NET 2.0 with Generics was released, I haven’t used a Hashtable one single time ever since. I always use the strongly typed generic collections and dictionary type classes instead, so that was probably what confused me.

Recap: If you want to remove an object completely from the Session, you should use the Session.Remove(“key”) method. It wont throw an exception if the key is not present in the Session.

Tag:

Add to Del.icio.us | Digg | Reddit | Furl

Bookmark WebProNews:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/

ASP.NET: Remove Unused Objects From the Session
Comments Off
About Mads Kristensen
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/ WebProNews Writer
Top Rated White Papers and Resources

Comments are closed.