Expiration Date Reset/Overriden on App Fabric Cache Provider

283 Views Asked by At

I am using

Microsoft.ApplicationServer.Caching.DataCache for caching

The problem is when I first add an item to the cache it preserves the time out but if I replace the existing item the cahce overrides the timeout to the default value. Here is the code I am using.

DataCache cache= new MyDataCahce();
// time out 30 secs
cache.Add("key",10, TimeSpan.FromMilliseconds(30000));
var temp = _cache.GetCacheItem("key");
temp.Timeout(); // minutes =  30 seconds which is correct

// Second time replace object at key
cache.Put("key",20)
var temp = _cache.GetCacheItem("key");
temp.Timeout(); // timeout reset to default and equals 10 minutes which is the default
2

There are 2 best solutions below

0
Helen Araya On BEST ANSWER

What I ended up doing is getting the timeout of the existing item before I add new item to the Cache.

 DataCache cache= new MyDataCahce();
    // time out 30 secs at first
    cache.Add("key",10, TimeSpan.FromMilliseconds(30000));
    var temp = _cache.GetCacheItem("key");
    temp.Timeout(); // minutes =  30 seconds which is correct


    // Second time replace object at key may be after 10 seconds
    var temp = _cache.GetCacheItem("key");
if(temp!=null) // it is not expired yet
{
    var timeOut = temp.Timeout();  // less than 30 seconds should be about 20 seconds
    cache.Put("key",20, timeOut )
    var temp = _cache.GetCacheItem("key");
    temp.Timeout(); // timeout less than 30 seconds 
}
2
stuartd On

As you have noted - and as documented - that Put method "Adds or replaces an object in the cache"

So you must therefore use the overload of Put which allows you to specify the timespan, i.e.:

cache.Put("key", 20, TimeSpan.FromMilliseconds(30000));