Caveat on Caching in ASP.NET

If you are working with the System.Web.Caching.Cache component in ASP.NET, there is something you should probably know. The cache is not a virtual location where data is being stored; instead, the cache is a collection, and as such, the objects being put into it are being put in by reference, not by value.

I was working with a client today and they were experiencing an issue that no one could figure out. I dug into it, and discovered that they were doing the following:

1) Creating an System.Xml.XmlDocument object and loading it with data
2) Inserting this object into the cache
3) Removing some nodes from the object


Following a page transition, they were pulling the document back out of the cache, and they could not understand why nodes seemed to be disappearing. This is when I explained how the cache works, and that is it not saving a representation of the object when it is inserted into the cache, but rather putting the object into the cache collection.

Just a good thing to know if you plan to be caching and changing objects. Good luck out there!

0 comments:

Post a Comment