MemoryCache in System.Runtime.Caching: items don't expire

4.6k Views Asked by At

I currently try to insert items into the MemoryCache.Default instance, which works. But the items don't expire! Polling interval is on default setting 2 minutes, no specific settings have been done for MemoryCache.

Add item routine is like this:

string key = "someKey";
var faultyItem = GetFaultyItemToBlockFromProcessingTheNextThreeMinutes();

if (!MemoryCache.Default.Contains(key))
{
    MemoryCache.Default.Add(
        new CacheItem(key, faultyItem),
        new CacheItemPolicy() 
        { 
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(3)
        });
}

However, the items never expire in cache! I waited for more than 10 minutes, and they're still there in the cache. Main purpose is to prevent them from flooding the database with queries, by attempting to process them every few seconds. They are checked every couple of seconds, but don't have a SlidingExpiration. They should be checked again after roughly 3 minutes, 5 minutes as a max delay would still be tolerable.

I don't want to do any configuration outside code, in XML or such. If it's not possible, is there a good alternative to MemoryCache? Perhaps with numeric/object keys and configuration through parameters and properties?

1

There are 1 best solutions below

0
On

I setup a simple trial application from scratch with the code snippet from your question. The only modification that I made was the following: var faultyItem = "test";

Putting a watch on the statement MemoryCache.Default.Contains(key) confirms that after 3 minutes, that item was evicted from the cache, as that statement returned false.

One possibility is that somewhere else in your application, you have already put an item into the MemoryCache using the same key that does not have an expiry, so it is never falling out, and is never being updated with a new item that does have an absolute expiry. Apart from searching your app, one way to test for this would be to use a named cache instead of the default cache for this specific operation to identify potential shared use. i.e. static MemoryCache testCache = new MemoryCache("TestCache").