| by Arround The Web | No comments

How to Implement MemoryCache for Caching in C#

There is one technique that pops into our minds when we think of enhancing the performance of an application: caching.

Caching is an incredible feature that can help to optimize and enhance the performance and scalability of an application. Caching involves storing a copy of copies of a result or file in a strategic location that are very fast and efficient for the application to access. This, in turn, helps reduce the response time and the workload on the remote machine.

In this tutorial, we will learn the basics of setting a caching mechanism when dealing with C# application using the “MemoryCache” class.

Add a MemoryCache Package

Before we can implement and use the “MemoryCache” class, we need to ensure that we have the Microsoft.Extensions.Caching.Memory package installed.

Run the command as follows:

NuGet\Install-Package Microsoft.Extensions.Caching.Memory -Version 7.0.0

This should download and install the caching package in your project.

The following shows the syntax of the “MemoryCache” class:

public class MemoryCache : System.Runtime.Caching.ObjectCache, IDisposable

Example: Implementation and Use of MemoryCache

To better understand how to use the “MemoryCache” class, let us work with a basic example as shown in the following:

using System;
using Microsoft.Extensions.Caching.Memory;

namespace MemoryCacheExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1
            var cache = new MemoryCache(new MemoryCacheOptions());

            // 2
            cache.Set("CurrentTime", DateTime.Now, DateTimeOffset.Now.AddSeconds(5));

            // 3
            if (cache.TryGetValue("CurrentTime", out DateTime currentTime))
            {
                Console.WriteLine($"Cached Time: {currentTime}");
            }

            // 4
            Console.WriteLine("Waiting for cache item to expire...");
            System.Threading.Thread.Sleep(6000);
            // 5
            if (cache.TryGetValue("CurrentTime", out currentTime))
            {
                Console.WriteLine($"Cached Time: {currentTime}");
            }
            else
            {
                Console.WriteLine("Cache item expired");
            }
        }
    }
}

Let us explain:

1. In this block, we create a new instance of the “MemoryCache” class. We also use the MemoryCacheOptions to configure the cache settings. For our case, we use the default settings for demonstration purposes.

The MemoryCacheOptions supports the following options:

2. In the second part, we use the “Set” method to add the items to the cache. The method accepts a key which is used to identify the item. The second parameter is the item that we wish to add to the cache, and the third denotes the expiration duration. In this case, the value is removed from cache after five seconds.
3. Third, we use the “TryGetValue” method to retrieve the items from the cache. The method returns true if the value is found. Otherwise, it returns false. The “out” parameter allows us to fetch the actual value.

If we run the previous code, we should get an output as follows:

Cached Time: 10/11/2023 10:54:35 PM

Waiting for cache item to expire…

Cache item expired

Conclusion

This tutorial guided you through the most fundamental concepts of working with the “MemoryCache” class in C# to implement caching.

Share Button

Source: linuxhint.com

Leave a Reply