DEV Community

Cover image for C# - Caching Data with MemoryCache
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Caching Data with MemoryCache

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.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We create a MemoryCache instance using MemoryCache.Default. You can also create custom cache instances with specific settings if needed.

  2. We define a cache key (cacheKey) and the data (cachedData) that we want to cache.

  3. We set up a CacheItemPolicy that 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.

  4. We add the data to the cache using cache.Add and provide the cache key, data, and cache policy.

  5. To retrieve data from the cache, we use cache.Get and 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)