Implementing a data cache in C# can significantly improve the performance of your applications by reducing the number of times data needs to be fetched from a slower data store, such as a database or an external API. This example will demonstrate a simple in-memory caching mechanism using the MemoryCache
class from the System.Runtime.Caching
namespace.
using System;
using System.Runtime.Caching;
public class DataCache
{
private MemoryCache _cache;
public DataCache()
{
_cache = MemoryCache.Default;
}
public T GetData(string key, Func fetchFunc, DateTimeOffset? absoluteExpiration = null)
{
if (_cache.Contains(key))
{
return (T)_cache.Get(key);
}
var data = fetchFunc();
_cache.Add(key, data, absoluteExpiration ?? DateTimeOffset.Now.AddMinutes(10));
return data;
}
public void Remove(string key)
{
_cache.Remove(key);
}
}
// Usage Example:
// var dataCache = new DataCache();
// var data = dataCache.GetData("myKey", () => FetchFromDataSource());
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?