0

I use the MemoryCache library in an ASP.NET Core project to create a cache, following the Microsoft documentation (https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-6.0). The problem is that when the cache is full and i try to add a new element in the cache (using the Set() function), it removes one element from the cache and doesn't add the new one. Also it is not clear on the basis of what the library deletes the elements present in the cache, it seems to act randomly and not based on the life time of the elements. I also tried to set all the elements in the cache with the same priority (CacheItemPriority.Normal). How can I solve the problem?

var calendarCacheEntryOptions = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(120))
            .SetAbsoluteExpiration(DateTime.Now.AddSeconds(3600))
            .SetPriority(CacheItemPriority.Normal)
            .SetSize(1);

_calendarCache.Set(id, hashCode, calendarCacheEntryOptions);
1
  • Is there any evidence for the problem you describe? As it sounds very strange, updates are welcome in the post. Commented May 24, 2022 at 8:50

1 Answer 1

0

In that same link it later goes on to describe: Expiration doesn't happen in the background. There's no timer that actively scans the cache for expired items. Any activity on the cache (Get, Set, Remove) can trigger a background scan for expired items. You may want to re-evaluate your sizing (or if you need sizing at all), or the absolute expiration value.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! However, it is strange that invoking the Set() function when the cache is full does not add the new element to the cache, but only takes care of removing an element from the cache to make room for the new one
Yeah, I would agree. By their description, 'Any activity on the cache (Get, Set, Remove) can trigger a background scan for expired items. ' it does sound like a timing thing though. Sounds like the Set will trigger the background task, but by then it is too late.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.