Junior — Middle
What is the role and purpose of functional interfaces in programming?
sobes.tech AI
Answer from AI
To implement caching in C# projects, I used several approaches and tools:
- MemoryCache from the
System.Runtime.Cachingnamespace for in-memory data caching. - Distributed cache (e.g., Redis) for caching in a distributed environment, useful for scaling.
- Using caching attributes in ASP.NET Core, such as
[ResponseCache], for HTTP response caching. - Implementing a custom cache layer using dictionaries and timeouts for specific tasks.
Example of using MemoryCache:
using System.Runtime.Caching;
MemoryCache cache = MemoryCache.Default;
string cacheKey = "user_123";
var userData = cache.Get(cacheKey);
if (userData == null)
{
userData = GetUserFromDatabase(123); // method to get data
cache.Set(cacheKey, userData, DateTimeOffset.Now.AddMinutes(10));
}
// Use userData
This approach helps reduce database load and improve application performance.