Sobes.tech
Junior — Middle

Milliseid lähenemisviise või tööriistu kasutasite andmete vahemälu rakendamiseks?

sobes.tech AI

Vastus AI-lt

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

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

  • IMemoryCache and IDistributedCache from ASP.NET Core — for caching in web applications. IMemoryCache is a local cache, IDistrubutedCache is for distributed cache (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 database
    cache.Set(cacheKey, user, DateTimeOffset.Now.AddMinutes(10));
}
// use user

This approach reduces the number of database calls and improves performance.