Sobes.tech
Junior — Middle

What approaches or tools have you used for data caching?

sobes.tech AI

Answer from AI

For caching data in C#, I often use several approaches:

  • MemoryCache from the System.Runtime.Caching namespace — for local in-memory cache within the application. It allows setting cache lifetime, priorities, etc.

  • IMemoryCache and IDistributedCache from ASP.NET Core — for caching in web applications. IMemoryCache is a local cache, while IDistributedCache is for distributed caching (e.g., Redis).

  • External cache systems like Redis or Memcached for scalable and distributed caching.

Example of using MemoryCache:

using System.Runtime.Caching;

var cache = MemoryCache.Default;
string cacheKey = "user_123";
var user = cache.Get(cacheKey) as User;
if (user == null)
{
    user = GetUserFromDatabase(123); // method to get from DB
    cache.Set(cacheKey, user, DateTimeOffset.Now.AddMinutes(10));
}
// use user

This approach reduces database access and improves performance.