CacheDependency from 2 or more other cache elements. (ASP.NET MVC3)

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

I would like to add elements to HttpRuntime.Cache so that the elements are invalid if I modify other elements in the cache. Dependencies must be defined by the key.

I need 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 with this.

+6
source share
1 answer

I did not know that you can do this, but if you look at the CacheDependency constructor here , you will see that the second parameter is an array of cache keys, so if any of these cached elements change, the whole dependency will be changed, and your dependent item will also be invalid.

So your code would be something like this:

 String[] cacheKeys = new string[]{"cacheKey1","cacheKey2"}; var dep = New CacheDependency("", cacheKeys); HttpRuntime.Cache.Add(itemDescriptor, ret, dep ...); 
+7
source

Source: https://habr.com/ru/post/898502/


All Articles