Junior — Middle
What methods or tools have you used to implement caching in your projects?
sobes.tech AI
Answer from AI
For implementing 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, which is useful for scaling.
- Using caching attributes in ASP.NET Core, such as
[ResponseCache]for caching HTTP responses. - 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 retrieve data
cache.Set(cacheKey, userData, DateTimeOffset.Now.AddMinutes(10));
}
// Use userData