Can't add item to memory cache after item expires

I am using a memory cache to prevent reprocessing of messages that I receive from the queue.

This is how I create cache and add items:

        _cache = new MemoryCache("TransactionProcessorCache");

        _policy = new CacheItemPolicy
        {
            UpdateCallback = null,
            AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(1)
        };

        _cache.Add("unique key", "value", _policy);

      

I add the first item to the cache and I can get that item within 1 minute which is expected.

But, once the first item expires and the cache becomes empty, subsequent items that I add to the cache cannot be recovered. The cache always behaves as if it were empty, despite receiving a "true" return value from a call to _cache.Add (...).

I am using .NET Framework 4.5.1. The application is a console application. MemoryCache is System.Runtime.Caching

+3


source to share


2 answers


Look at this line again

AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(1)

      



You will disable the cache after 1 min from the current time forever . After one minute, you will have to re-create the policy again (or create the policy every time you want to add an item and then behave as you expect).

See @ JD.B's answer for better usage policy.

+2


source


@ Sinatr's answer clears it up; the AbsoluteExpiration policy expires on the policy itself. This means that you will need to create a new policy for every item you add; as @Sinatr said in his answer.

Meanwhile, the SlidingExpiration policy keeps track of the last access to an item and only removes that item if it was not available within the specified time. This way, you can reuse the same policy, but it has slightly different behavior because the item's expiration timer is reset every time it is accessed.



SlidingExpiration example:

MemoryCache cache = new MemoryCache("C");
CacheItemPolicy policy = new CacheItemPolicy
{
    UpdateCallback = null,
    SlidingExpiration = new TimeSpan(0, 0, 5)
};

cache.Add("key", "value", policy);
Console.WriteLine("1) " + cache.Get("key")); // Prints `1) value`

System.Threading.Thread.Sleep(5250); // Wait for "key" to expire
Console.WriteLine("2) " + cache.Get("key")); // Prints `2) `

// Just showing the the cache policy still works once an item expires.
cache.Add("key2", "value2", policy);
Console.WriteLine("3) " + cache.Get("key2")); // Prints `3) value2`

System.Threading.Thread.Sleep(5250); // Wait for "key2" to expire
Console.WriteLine("4) " + cache.Get("key2")); // Prints `4) `

      

+1


source







All Articles