Thread: Caching
View Single Post
  #4 (permalink)  
Old May 29th, 2010, 03:24 AM
Imar's Avatar
Imar Imar is offline
Wrox Author
Points: 72,073, Level: 100
Points: 72,073, Level: 100 Points: 72,073, Level: 100 Points: 72,073, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,587 Times in 1,563 Posts

Cool. So as long as the application isn't recycled, you can fetch "whatever" from the Cache object days later?
No, that's not true. It might be there, it might not.
Objects created in your code and stored in the Cache will remain there until a) they expire due to one of their constraints, b) the cache decides to ditch them or c) the application restarts.
Stuff you store in the cache isn't necessarily there forever. You can put restrictions on its lifetime or ASP.NET may decide to delete it. You should always check if it's there. E.g.:

SomeClass myInstance = Cache["SomeKey"] as SomeClass;
if (myInstance == null)
  myInstance = WhatEverItTakesToCreateMyInstance();
  Cache.Insert("SomeKey", myInstance);
Note that the Cache has Add and Insert methods with various overloads to determine lifetime, dependencies and expiration policies.

Does it become part of the application state as well, and can it be fetched days later (again provided the application isn't recycled in between)?
Yes, in this case it stays there until the application is restarted. Indeed, static fields are tied to the application domain so anything you store in a static field is available during the lifetime of the app domain.

The nice thing about the cache is that it can do memory management for you. E.g. stuff that consumes a lot of money and / or that is infrequently used can be thrown out of the cache, something you cannot accomplish with static fields.


Imar Spaanjaars
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
The Following User Says Thank You to Imar For This Useful Post:
chroniclemaster1 (May 30th, 2010)