Caching is a powerful technique to improve the performance and responsiveness of your applications by storing frequently accessed data in memory. The MemoryCache class in C# provides a flexible and efficient way to implement caching.
using System;
using System.Runtime.Caching;
class Program
{
static void Main()
{
// Create a MemoryCache instance
var cache = MemoryCache.Default;
// Define cache key and data
string cacheKey = "MyCachedData";
string cachedData = "This data is cached.";
// Add data to the cache with an expiration time of 5 minutes
CacheItemPolicy cachePolicy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5)
};
cache.Add(cacheKey, cachedData, cachePolicy);
// Retrieve data from the cache
string retrievedData = cache.Get(cacheKey) as string;
if (retrievedData != null)
{
Console.WriteLine("Data retrieved from cache: " + retrievedData);
}
else
{
Console.WriteLine("Data not found in cache.");
}
}
}
In this example:
We create a
MemoryCacheinstance usingMemoryCache.Default. You can also create custom cache instances with specific settings if needed.We define a cache key (
cacheKey) and the data (cachedData) that we want to cache.We set up a
CacheItemPolicythat specifies an absolute expiration time of 5 minutes for the cached item. You can configure other cache policies such as sliding expiration, change monitoring, or removal callbacks as needed.We add the data to the cache using
cache.Addand provide the cache key, data, and cache policy.To retrieve data from the cache, we use
cache.Getand cast the retrieved object to its original type. If the data exists in the cache, we display it; otherwise, we indicate that the data was not found.
Using MemoryCache allows you to store frequently used data in memory, reducing the need to recompute or fetch data from slower data sources, such as databases or web services. This can significantly improve the performance and responsiveness of your applications, especially for data that doesn't change frequently.
Top comments (0)