0

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
Helen Araya
  • 1,886
  • 3
  • 28
  • 54

2 Answers2

0

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));
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • I know there is such method with Timeout. My issue is that when I go to there to replace the existing key value the timeout may have elapsed and I don't know what it is by the time I want to replace I can't simply put 30000. – Helen Araya Oct 21 '15 at 15:41
  • 1
    Ah, that wasn't not clear from your question. I don't quite understand why you would do this, but it sounds like you will have to get the item, determine how much timeout is left, and set it to that. – stuartd Oct 21 '15 at 15:55
0

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 
}
Helen Araya
  • 1,886
  • 3
  • 28
  • 54