I have a method which generates our cache key which is a string like below:
private static readonly HashSet<string> CacheKeys = new HashSet<string>();
public string Generate(int clientId, int processId)
{
StringBuilder sb = new StringBuilder();
sb.Append("data:").Append("c:").Append(clientId).Append("::");
sb.Append("pi::").Append(processId);
// do I need to store everything in my CacheKeys?
// or this can be improved so that I can fullfill below 3 requirements
// CacheKeys.Add(sb.ToString());
return sb.ToString();
}
And then this string gets cached in MemoryCache as a key along with their value (not shown here as it is not relevant).
_memoryCache.Set<T>(cacheKey, value, memoryCacheOptions);
I have a requirement where I need to delete a specific key
or keys
from the memory cache depending on below requirement-
- I need to delete specific
processId
+clientId
key from the memory cache. - I need to delete all keys matching specific
clientId
key from the memory cache regardless ofprocessId
. - I also need to delete all the keys matching a particular
processId
key from the memory cache regardless ofclientId
.
Now after reading on SO and MemoryCache
tutorial, it looks like there is no way to iterate over all the keys (or find keys matching particular regex pattern) and remove it from the cache.
Problem Statement
After going through various link it looks like I need to store my cache keys in separate data structure and then use that to remove it.
- How should I store my
cacheKey
in such a way in the above method so that I can remove a key basis on above 3 requirements easily by iterating this data structure or any thread safe data structure? - Also the input structure which specifies what keys to remove (following above 3 pattern) is coming from some other service and that is not defined as well and I am pretty much open to represent in any format which can help me to do this task efficiently.
Basically I am trying to come up with an example for all my above three patterns by which I can remove the keys efficiently from MemoryCache
which uses RemoveByPattern
or Remove
method. As of now I am not able to figure out on how to prepare an example or test cases for all those three cases which can use my RemoveByPattern
or Remove
method and clear the keys efficiently.
public void RemoveByPattern(MemoryCache memoryCache, string pattern)
{
var keysToRemove = CacheKeys
.Where(k => Regex.IsMatch(k, pattern, RegexOptions.IgnoreCase))
.ToArray();
foreach (var ktr in keysToRemove)
Remove(memoryCache, ktr);
}
public void Remove(MemoryCache memoryCache, string key)
{
memoryCache.Remove(key);
CacheKeys.Remove(key);
}
How can I represent my input structure in such a way which can understand my above three requirements and then feed it to RemoveByPattern
or Remove
method easily?