Caching in C#: Redis, Memcached, and Built-in .NET Solutions

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in C#: Redis, Memcached, and Built-in Solutions for .NET



Caching is one of the key tools for improving the performance of C# applications. It allows you to reduce response time, decrease load on databases and external APIs. The .NET ecosystem offers several approaches: from the built-in MemoryCache to distributed solutions based on Redis and Memcached. In this article, we will analyze each option, show code examples, and provide recommendations for selection.



1. Built-in Caching: MemoryCache and IDistributedCache



The .NET platform provides two main abstract mechanisms for working with cache: IMemoryCache (in-process) and IDistributedCache (distributed).



1.1 IMemoryCache

Stores data in the process memory. Ideal for single-threaded or monolithic applications where synchronization between multiple servers is not required. Easy to configure and requires no external dependencies.



// Adding to DI (Program.cs)builder.Services.AddMemoryCache();

// Usage in a servicepublic class WeatherService{ private readonly IMemoryCache _cache;

public WeatherService(IMemoryCache cache) { _cache = cache; }

public async Task<string> GetWeatherAsync(string city) { string cacheKey = $"weather_{city}"; if (_cache.TryGetValue(cacheKey, out string cachedData)) { return cachedData; }

// Emulating a long request await Task.Delay(2000); string result = $"Weather in {city}: +25°C";

var options = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)) .SetSlidingExpiration(TimeSpan.FromMinutes(2));

_cache.Set(cacheKey, result, options); return result; }}


1.2 IDistributedCache

An abstraction for distributed cache. Allows easy switching between providers (Redis, SQL Server, NCache) without changing business logic. By default, stores data as byte[].



// Registration (Program.cs) - using Redisbuilder.Services.AddStackExchangeRedisCache(options =>{    options.Configuration = "localhost:6379";});

// Usagepublic class ProductService{ private readonly IDistributedCache _cache;

public ProductService(IDistributedCache cache) { _cache = cache; }

public async Task<Product> GetProductAsync(int id) { string cacheKey = $"product_{id}"; var cachedBytes = await _cache.GetAsync(cacheKey);

if (cachedBytes != null) { return JsonSerializer.Deserialize<Product>(cachedBytes); }

// Database query var product = await GetProductFromDb(id);

var options = new DistributedCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromHours(1));

var serialized = JsonSerializer.SerializeToUtf8Bytes(product); await _cache.SetAsync(cacheKey, serialized, options);

return product; }}


2. Redis: Distributed Cache with Advanced Capabilities



Redis is the most popular caching solution in .NET. It operates as a high-performance in-memory store with support for complex data structures (lists, hashes, sets).



2.1 Installation and Configuration

To connect Redis to .NET, use the package Microsoft.Extensions.Caching.StackExchangeRedis.



dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis


2.2 Example with Redis and IDistributedCache

In addition to basic caching, Redis allows you to implement:

  • User sessions — storing session data between requests.
  • Locks

Blogs

Book Recommendations