Junior — Middle
Explain the working principle of Cache Sliding Expiration mechanism and its purpose.
sobes.tech AI
Answer from AI
The Cache Sliding Expiration mechanism is used to manage the lifetime of cached data. Unlike absolute expiration, where an item is removed from the cache after a fixed time since it was added, Sliding Expiration updates the lifetime of an item each time it is accessed.
This means that if an item in the cache is not used for a specified interval, it is removed. But if the item is accessed regularly, its lifetime is extended, and it remains in the cache.
This is useful for data that should stay in the cache as long as it is actively used and should be automatically removed when it becomes outdated.
Example in C# using MemoryCache:
var cache = MemoryCache.Default;
var policy = new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(10) // the item will be removed if not accessed for 10 minutes
};
cache.Set("key", "value", policy);
// Each time cache.Get("key") is called, the lifetime of the item is updated