Cache Absolute Expiry problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rakesh Shukla

    Cache Absolute Expiry problem

    Hi all,

    I have one question. I want to put a class which has one dictionary property in the cache. And I want this cached data should expire after 5 minutes by using absolute expiry.

    But I have one issue suppose one user is reading the Dictionary data from the cache and say 5 minutes over and the cached data is removed then while reading the data there may get object null reference error. Can anybody suggest me in this scenario how to proceed.
  • balabaster
    Recognized Expert Contributor
    • Mar 2007
    • 798

    #2
    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:

    Code:
    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:

    Code:
    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:
    Code:
    MyClass stuff = (MyClass)cache["stuff"];
    string prop1 = stuff.Property1;
    string prop2 = stuff.Property2;

    Comment

    Working...