views:

59

answers:

2

How can i make a cached object re-cache it self with updated info when the cache has expired? I'm trying to prevent the next user who request the cache to have to deal with getting the data setting the cache then using it is there any background method/event i can tie the object to so that when it expires it just calls the method it self and self-caches.

+1  A: 

You can use callback from Cache

System.Web.Caching.CacheItemRemovedCallback callback = 
    new System.Web.Caching.CacheItemRemovedCallback (OnRemove);
Cache.Insert("key",myFile,null, 
   System.Web.Caching.Cache.NoAbsoluteExpiration, 
   TimeSpan.Zero, 
   System.Web.Caching.CacheItemPriority.Default, callback);
 . . .
public static void OnRemove(string key, 
   object cacheItem, 
   System.Web.Caching.CacheItemRemovedReason reason)
   {
      // Logic
   }
vittore
The issue i'm facing now with this implementation is that its stating HttpContext.Current.Cache is not available.
BlackTea
try using `HttpContext.Current != null ? HttpContext.Current.Cache : HttpRuntime.Cache;`
vittore
A: 

Pardon me, maybe I'm missing something. But the sounds like you are after to keep update the cached data. IMO, it's better to use CacheDependency instead of expiration in this case. Of course, you have to re-cache it on the next request.

Mehdi Golchin
The idea is to re-cache every xmin with out having the next request come in and have to manually kick off the re-caching.
BlackTea