Caching in C# (.NET): Redis, MemoryCache and Other Tools
In modern high-load applications in C# (.NET), caching is one of the key mechanisms for improving performance and reducing database load. In this article, we will take a detailed look at the main caching tools in the .NET ecosystem: the built-in MemoryCache, distributed cache based on Redis via the StackExchange.Redis library, as well as the IDistributedCache abstraction.
1. Built-in Caching: MemoryCache
MemoryCache (namespace Microsoft.Extensions.Caching.Memory) is the simplest way to cache data directly in the process's RAM. It is ideally suited for single-process applications (e.g., ASP.NET Core without scaling).
Basic usage example:
using Microsoft.Extensions.Caching.Memory;
// Create cacheIMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
// Write to cache with a 5-minute lifetimecache.Set("user:123", new User { Id = 123, Name = "Ivan" }, TimeSpan.FromMinutes(5));
// Read from cacheif (cache.TryGetValue("user:123", out User user)){ Console.WriteLine($"User: {user.Name}");}else{ Console.WriteLine("Cache is empty, loading from DB...");}Advantages: maximum speed, zero network latency, easy setup.
Disadvantages: data lives only in one process, lost upon application restart.
2. Distributed Caching: Redis + StackExchange.Redis
For distributed systems (multiple servers, microservices), an external cache is required. Redis is the most popular choice. The main library for working with Redis in .NET is StackExchange.Redis (over 6,000 stars on GitHub).
Installation:
dotnet add package StackExchange.RedisExample of working with Redis:
using StackExchange.Redis;
// Connect to RedisConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379");IDatabase db = redis.GetDatabase();
// Write string with TTL (time to live)db.StringSet("session:token123", "user_data_here", TimeSpan.FromHours(1));
// Readstring data = db.StringGet("session:token123");if (!string.IsNullOrEmpty(data)){ Console.WriteLine($"Data from cache: {data}");}
// Caching complex objects (serialization to JSON)var product = new Product { Id = 1, Name = "Laptop", Price = 75000 };string json = System.Text.Json.JsonSerializer.Serialize(product);db.StringSet("product:1", json, TimeSpan.FromMinutes(10));
// Deserialization when readingstring cachedJson = db.StringGet("product:1");var cachedProduct = System.Text.Json.JsonSerializer.Deserialize<Product>(cachedJson);Additional Redis capabilities:
- Hashes — for storing objects with fields (e.g., user profile).
- Lists and sets — for queues, ratings.
- Pub/Sub — for cache invalidation notifications.
- Lua scripts — atomic operations.
3. IDistributedCache Abstraction
Microsoft provides the IDistributedCache interface (package Microsoft.Extensions.Caching.Abstractions), which allows switching between different cache implementations without changing application code.
Implementations:
MemoryDistributedCache— for development and testing (stores in memory).RedisCache(packageMicrosoft.Extensions.Caching.StackExchangeRedis) — for production.SqlServerCache
Also in library
Working with Excel in Go (Golang): Excelize, xlsx, tealeg libraries
JWT Tokens in PHP: Complete Guide to Authentication and Authorization
StoreKit for Swift: Complete Guide with Examples
HTML Parsing in PHP: A Complete Guide to Libraries and Tools
Event Bus and Observer Pattern in Java: A Guide with Examples