asp.net webservice cache extend expiration

1k Views Asked by At

I haven't found anything so I dont believe what I want is possible. I want to reset the sliding expiration of a cache variable every time it is accessed.

public class MyCache
{
public static object CachedItem
{
    get
    {
        string key = "item11"; // users share the object at this key
        object o = Cache[key];

        //re-set the timer janky way
        //triggers callback, which I dont want
        o = (o == null) ? new object() : Cache.Remove(key);
        Cache.Add(key, o, null, Cache.NoAbs..., new TimeSpan(0,5,0), High, Removed);

        return o;
    }
}

private static void Removed(string key, object value, CacheItemRemovedReason reason)
{
    // audit MySql table
    // no good because Cache.Remove is getting called manually a lot.
}
}

In practice the cache item is a list of messages in a chat room. When a message is added I want the chatroom to "stay alive" a little bit longer. alternate methods also welcome.

1

There are 1 best solutions below

0
On BEST ANSWER

The cache object by design will automatically reset the expiration each time it is accessed. All you should have to do is try to get the object, if its null, set it with the sliding expiration like you have now, if not null return it. Just by getting it, the expiration is reset. Like so

public static object CachedItem
{
    get
    {
        string key = "item11"; // users share the object at this key
        object o = Cache[key];
        if (o == null)
        {
            o = {Get from some source};
            Cache.Add(key, o, null, Cache.NoAbs..., new TimeSpan(0,5,0), High, Removed);
        }

        return o;
    }
}