Pergunta

I'm a little puzzled over the possible cachedependencies in asp.net, and I'm not sure how to use them.

I would like to add items to the HttpRuntime.Cache in a way, that the elements should invalidate if I change other elements in the cache. The dependencies should be defined by the key.

I want a function like this:

public MyObject LoadFromCache(string itemDescriptor, IEnumerable<string> dependencies)
{
    var ret = HttpRuntime.Cache[itemDescriptor] as MyObject;
    if (ret == null)
    {
        ret = LoadFromDataBase(itemDescriptor);

        //this is the part I'm not able to figure out. Adding more than one dependency items.
        var dep = new CacheDependency();
        dependencies.ForEach(o => dep.SomeHowAdd(o));

        HttpRuntime.Cache.Add(
            itemDescriptor, 
            ret, 
            dependencies, 
            System.Web.Caching.Cache.NoAbsoluteExpiration, 
            System.Web.Caching.Cache.NoSlidingExpiration, 
            Caching.CacheItemPriority.Normal, 
            null
        );
    }
    return ret;
}

Help me out on this one.

Foi útil?

Solução

I didn't know you could do this, but if you look at the CacheDependency constructor here, you can see that the second parameter is an array of cache keys, so that if any of those cached items change, the whole dependency will be changed and your dependent item will be invalidated as well.

So your code would be something like:

String[] cacheKeys = new string[]{"cacheKey1","cacheKey2"};
var dep = New CacheDependency("", cacheKeys);

HttpRuntime.Cache.Add(itemDescriptor, ret, dep ...);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top