Removing multiple cache keys based on matching criteria

Topics: Caching Application Block
Nov 18, 2011 at 9:22 AM
Edited Nov 18, 2011 at 9:40 AM

Hi,

I'm using ent lib 5.0 caching block. My question is How can we remove multiple cache keys based on some matching criteria in one go?

I'm trying something like below code but its giving an error as because "Keys" is not recognised keyword. Even cache.Keys is not recognisable.

Looping through cache keys seems to be not working in ent lib caching :-(

public static void RemoveUserSpecificCacheKeys(string cacheUserSpecificKey)
    {
        ICacheManager cache = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>();

        List<string> keysToRemove = new List<string>();

        foreach (var key in Cache.Keys)
        {
            if (key.Contains(cacheUserSpecificKey))
            {
                keysToRemove.Add(key);
            }
        }

        foreach (var key in keysToRemove)
        {
            cache.Remove(key);
        }
    }


Any Help?

Regards

Bhupinder

Nov 20, 2011 at 2:16 AM

There is no out of the box support for retrieving all Keys of the CacheManager.

If you really need this behavior you could try to rethink your "key" design.  E.g. use multiple CacheManager instances to store specific keys.

Based on your code it looks like you are trying to cache some information on a per user basis.  To do that you could use dynamic cache managers.  See this stackoverflow question for more information on how to do that.  Note there is no automatic way to free unused caches so there could be memory implications with that approach.

Another option would be to extend the block and implement your own custom CacheManager to provide the functionality that you wish.  It should be fairly straight forward to reuse the current CacheManager implementation (see the source code) to provide the needed properties.  The Cache object actually already has a property CurrentCacheState that returns a Hashtable which will allow you to get the Keys so it would just be a matter of surfacing that information on the CacheManager. 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com