When the item is removed from the cache, it doesn't destroy the object. The cache should just hold a reference to the object.
Check this simplified example:
- Hashtable cache = new Hashtable();
-
MyClass stuff = new MyClass
-
{
-
Property1 = "Hello",
-
Property2 = "World"
-
}
-
cache.Add("stuff", stuff);
When you added the item to the hashtable, it doesn't actually add the object, but a reference to the object. The memory address if you will [that's simplified, don't read this too literally]. So the object is held in memory somewhere and a reference is held in the cache. The reference in the cache stops garbage collection from throwing it out until the reference is removed, thus it will sit in memory until there's no references left. When someone needs to make use of it, the reference is retrieved from the cache in order to locate the object in memory and now there's 2 references to the object. The cache is invalidated and the reference is removed, leaving 1 reference - the reference that's in use. The object stops being used and the reference goes out of scope leaving 0 references. At this point garbage collection reclaims the memory space held by the object.
If you're getting a null reference exception, then it's because you're making reference to your object in an invalid manner.
This occurs when:
- string prop1 = cache["stuff"].Property1;
-
//Cache is invalidated here...
-
string prop2 = cache["stuff"].Property2; //Throws null reference exception
This can be avoided by doing this instead:
- MyClass stuff = (MyClass)cache["stuff"];
-
string prop1 = stuff.Property1;
-
string prop2 = stuff.Property2;