Caching
1. In-Memory Cache
In-Memory Cache stores data directly in the application's memory. This type of cache is very fast because the data is stored and accessed directly from RAM.
MemoryCache: The
MemoryCache
class in theSystem.Runtime.Caching
namespace provides a simple way to store and retrieve data from memory.Example:
IMemoryCache: In
Microsoft.Extensions.Caching.Memory
,IMemoryCache
is a service that provides a mechanism for storing data in memory in ASP.NET Core applications.
What are the key features of this library?
Strongly Typed: Unlike the earlier MemoryCache, IMemoryCache is strongly typed, reducing errors and improving code readability.
Dependency Injection Friendly: IMemoryCache is designed to be used with dependency injection, making it easy to manage and test.
Expiration Policies:
Absolute Expiration: The cache entry will expire after a set duration.
Sliding Expiration: The cache entry will expire if it's not accessed within a set duration.
Expiration Tokens: These allow cache entries to be evicted based on external triggers, like file changes.
Size Limitations: You can set a size limit for the cache and define the size for each entry, helping to manage memory usage effectively.
Eviction Callbacks: Callbacks can be registered to execute custom logic when a cache entry is evicted.
Thread Safety: IMemoryCache is thread-safe, allowing concurrent access by multiple threads.
Example:
2. Distributed Cache
Distributed Cache stores data on one or more external servers, allowing shared caching between multiple instances or applications.
Redis Cache: Redis is an in-memory data structure store that can be used as a distributed cache.
Example:
SQL Server Cache: Uses SQL Server to store cache data.
Example:
3. Output Cache
Output Cache stores the output of actions or entire pages in web applications.
Output Caching in ASP.NET MVC/Web API: Stores the result of controller actions to speed up HTTP responses for similar requests.
Example:
Response Caching Middleware in ASP.NET Core: Middleware that stores the results of HTTP requests to reuse for subsequent requests.
Example:
Summary
In C#, the common types of caching include:
In-Memory Cache: Using
MemoryCache
orIMemoryCache
.Distributed Cache: Using distributed systems like Redis or SQL Server.
Output Cache: Used in web applications to store the results of actions or pages.
Last updated