Caching in C# (.NET): Redis, MemoryCache and Alternatives
Caching is one of the key tools for improving the performance of C# (.NET) applications. It helps reduce response time, lower database load, and decrease infrastructure costs. In this article, we will cover built-in .NET mechanisms, popular implementations based on Redis, as well as alternative solutions such as NCache and Couchbase.
1. Built-in Caching: MemoryCache
MemoryCache (namespace Microsoft.Extensions.Caching.Memory) is a simple and fast cache that stores data in the RAM of a single process. It is ideal for single-threaded applications or web servers with a single instance.
Installation and Setup
dotnet add package Microsoft.Extensions.Caching.MemoryBasic Usage Example
using Microsoft.Extensions.Caching.Memory;
public class DataService{ private readonly IMemoryCache _cache; private readonly TimeSpan _cacheDuration = TimeSpan.FromMinutes(5);
public DataService(IMemoryCache cache) => _cache = cache;
public async Task<string> GetDataAsync(string key) { if (!_cache.TryGetValue(key, out string cachedData)) { cachedData = await FetchFromDatabaseAsync(key); _cache.Set(key, cachedData, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = _cacheDuration }); } return cachedData; }}Advantages and Disadvantages
- + Simplicity, zero network latency.
- + Built-in expiration support (absolute/sliding).
- - Does not work when scaling across multiple servers.
- - Cache is cleared upon application restart.
2. Distributed Caching: Redis
Redis is the most popular choice for distributed caching in the .NET ecosystem. It runs as a separate service accessible to all application instances. In .NET, the IDistributedCache abstraction is used.
Package Installation
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedisConfiguration in Program.cs
builder.Services.AddStackExchangeRedisCache(options =>{ options.Configuration = "localhost:6379"; options.InstanceName = "MyAppCache";});Example of Working with IDistributedCache
public class RedisCacheService{ private readonly IDistributedCache _cache;
public RedisCacheService(IDistributedCache cache) => _cache = cache;
public async Task SetAsync(string key, byte[] data, int minutes = 10) { await _cache.SetAsync(key, data, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(minutes) }); }
public async Task<byte[]> GetAsync(string key) { return await _cache.GetAsync(key); }}Advanced Redis Features
- Object Serialization: use
System.Text.JsonorNewtonsoft.Json. - Tag-based Invalidation: third-party libraries (e.g.,
EasyCaching.Redis) allow grouping entries. - Pub/Sub: for cache change notifications.
3. Alternatives to Redis
3.1 NCache
NCache is a commercial solution (with a free version) supporting .NET. It provides advanced features: synchronization between nodes, SQL-like queries to the cache, ASP.NET session caching.
- + Built-in support for
IDist
Also in library
Working with ZIP Archives in Go (Golang): Creating, Reading, and Extracting Files
Monitoring Swift Applications on iOS/macOS: Libraries and Tools
Multer for JavaScript (Node.js): Complete Guide with Examples
WebSocket Libraries for Node.js: ws, Socket.IO, uWS — Complete Overview