alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.72k stars 159 forks source link

Is there a way to cache in item forever ? #81

Closed EnricoMassone closed 5 years ago

EnricoMassone commented 5 years ago

Hi,

this is a very simple question indeed.

I would like to know if there is a built in way to cache an item forever (the cached item never expires, so it is never removed from the cache).

Is there a way to specify a never expiring item when it is added to the cache or the only way to do so is setting a very long absolute expiration (something like DateTimeOffset.Now.AddYears(1)) ?

Thanks for helping

DaveInCaz commented 5 years ago

I think this is described in the API docs section "Custom cache policies", where it shows in part:

var options = new MemoryCacheEntryOptions(){ 
   Priority = CacheItemPriority.NotRemovable
};

Dave

EnricoMassone commented 5 years ago

I think this is described in the API docs section "Custom cache policies", where it shows in part:

var options = new MemoryCacheEntryOptions(){ 
   Priority = CacheItemPriority.NotRemovable
};

Dave

I agree with you.

To summarize, the trick to cache an item forever is calling one of the methods of IAppCache allowing you to pass an instance of MemoryCacheEntryOptions.

In order to cache the item forever you have to do two things on the MemoryCacheEntryOptions instance:

Please notice that the Compact method is meant to be called by the developer, based on what I know it is never called automatically by the internals of the ASP.NET core MemoryCache as you can verify from this issue (https://github.com/aspnet/AspNetCore.Docs/issues/11216). This is true regardless of whether the SizeLimit property has been set on the MemoryCache instance.