Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dotnet Core In Memory Cache - what is the default expiration

I'm using MemoryCache in a dotnet core C# project. I'm using it store a list of enums that I read out of a collection (I want to store it since it uses reflection to load the enums which takes time).

However, since my collection isn't going to change, I don't want it to expire at all. How do I do that? If I don't set any Expiration (SlidingExpiration or Absolute Expiration), will my cache never expire?

like image 703
Rose Avatar asked Oct 05 '18 13:10

Rose


People also ask

What is in-memory cache in .NET Core?

In-Memory Caching in ASP.NET Core is the simplest form of cache in which the application stores data in the memory of the webserver. This is based on the IMemoryCache interface which represents a cache object stored in the application's memory.

Is MemoryCache a singleton?

Note that the MemoryCache is a singleton, but within the process. It is not (yet) a DistributedCache. Also note that Caching is Complex(tm) and that thousands of pages have been written about caching by smart people.

What is sliding expiration cache?

Sliding expiration ensures that if the data is accessed within the specified time interval the cache item life span will be extended by the interval value. For example, a session is added with 10 minutes expiration.

What is cache memory in asp net c#?

Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.


1 Answers

If you do not specify an absolute and/or sliding expiration, then the item will theoretically remain cached indefinitely. In practical terms, persistence is dependent on two factors:

  1. Memory pressure. If the system is resource-constrained, and a running app needs additional memory, cached items are eligible to be removed from memory to free up RAM. You can however disable this by setting the cache priority for the entry to CacheItemPriority.NeverRemove.

  2. Memory cache is process-bound. That means if you restart the server or your application restarts for whatever reason, anything stored in memory cache is gone. Additionally, this means that in web farm scenarios, each instance of your application will have it's own memory cache, since each is a separate process (even if you're simply running multiple instances on the same server).

If you care about only truly doing the operation once, and persisting the result past app shutdown and even across multiple instances of your app, you need to employ distributed caching with a backing store like SQL Server or Redis.

like image 121
Chris Pratt Avatar answered Oct 23 '22 00:10

Chris Pratt