I have a webpage which caches some querystring values for 30 seconds so that it does not receive duplicate values. I am using the following class:
public class MyCache {
private static ObjectCache cache = MemoryCache.Default;
public MyCache() { }
public void Insert(string key, string value)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.Priority = CacheItemPriority.Default;
policy.SlidingExpiration = new TimeSpan(0, 0, 30);
policy.RemovedCallback = new CacheEntryRemovedCallback(this.Cacheremovedcallback);
cache.Set(key, value, policy);
}
public bool Exists(string key)
{
return cache.Contains(key);
}
public void Remove(string key)
{
cache.Remove(key);
}
private void Cacheremovedcallback(CacheEntryRemovedArguments arguments)
{
FileLog.LogToFile("Cache item removed. Reason: " + arguments.RemovedReason.ToString() + "; Item: [" + arguments.CacheItem.Key + ", " + arguments.CacheItem.Value.ToString() + "]");
}
}
This has worked fine for a couple of weeks then suddenly the cache doesn't keep the values anymore. The CacheRemoved callback fires instantly after an item is inserted into cache and i get the removed reason: CacheSpecificEviction This is running on a Windows Server 2008 SP1, IIS7.5 with .NET 4.0. No changes were applied to the OS or IIS during this time.
Is there a way to solve this and if not, is there a better cache solution to use in a web page ?
Thank you in advance.
Looking at the source code of MemoryCacheStore
(that should be the default store used by MemoryCache.Default
) it seems that the remove callback with argument CacheSpecificEviction
is only called when the cache is disposed:
https://referencesource.microsoft.com/#System.Runtime.Caching/System/Caching/MemoryCacheStore.cs,230
Look around and make sure your cache object is not being disposed accidentally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With