'MemoryCache in ASP.NET Core doesn't set elements and acts randomly

I use the MemoryCache library in an ASP.NET Core project to create a cache, following the Microsoft documentation (https://docs.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);


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian W