Caching in C# (.NET): Redis and Other Tools for Speeding Up Applications
Caching is one of the most effective ways to improve the performance and scalability of C# (.NET) applications. In this article, we will thoroughly examine built-in caching mechanisms, popular libraries for working with Redis, as well as alternative solutions. You will learn how to choose the right tool for your task and avoid common mistakes.
Built-in Caching Mechanisms in .NET
The .NET platform provides several ready-made caching solutions that are suitable for most scenarios without installing third-party dependencies.
1. MemoryCache (System.Runtime.Caching)
Built-in in-process memory cache. Ideal for single-threaded applications or low loads. Data is stored in RAM and is automatically evicted when resources are low.
using System.Runtime.Caching;
public class MemoryCacheService{ private readonly MemoryCache _cache = MemoryCache.Default;
public T GetOrSet<T>(string key, Func<T> factory, int expirationMinutes = 5) { var cached = _cache.Get(key); if (cached != null) return (T)cached;
var result = factory(); var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(expirationMinutes) }; _cache.Set(key, result, policy); return result; }}2. IDistributedCache (Microsoft.Extensions.Caching)
An abstraction for distributed caching. Allows easy switching between Redis, SQL Server, NCache, and other providers. Recommended for microservices and cloud applications.
using Microsoft.Extensions.Caching.Distributed;using System.Text.Json;
public class DistributedCacheService{ private readonly IDistributedCache _cache;
public DistributedCacheService(IDistributedCache cache) { _cache = cache; }
public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> factory, int expirationMinutes = 10) { var cached = await _cache.GetStringAsync(key); if (cached != null) return JsonSerializer.Deserialize<T>(cached);
var result = await factory(); var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(expirationMinutes) }; await _cache.SetStringAsync(key, JsonSerializer.Serialize(result), options); return result; }}Redis: The King of Distributed Caching
Redis is a high-performance in-memory data store supporting strings, lists, hashes, sets, and other data structures. For .NET, the primary library is StackExchange.Redis.
Installing and Configuring StackExchange.Redis
Install the package via NuGet:
dotnet add package StackExchange.RedisExample of connection and basic operations:
using StackExchange.Redis;
public class RedisCacheService{ private readonly ConnectionMultiplexer _redis; private readonly IDatabase _db;
public RedisCacheService(string connectionString) { _redis = ConnectionMultiplexer.Connect(connectionString); _db = _redis.GetDatabase(); }
public async Task SetAsync(string key, string value, int expirationMinutes = 5) { await _db.StringSetAsync(key, value, TimeSpan.FromMinutes(expirationMinutes)); }
public async Task<string> GetAsync(string key) { return await _db.StringGetAsync(key); }}Advanced Redis Features
- Pub/Sub — notifications between services
- Sorted Sets — ratings and leaderboards