Implement In-memory caching in .NET

Caching is the process of storing data that is frequently used. Caching can significantly improve the performance and scalability of an application. In-memory cache stores data in the memory of a web server where the web application is hosted. In-memory cache can be used for the short term, in cases where developers must use data in the application or sometime after it has been used. In this article, we will explain .NET’s InMemoryCache with code examples.

Creating InMemoryCache in C#

C# memorycache uses the namespace System.Runtime.Caching. To include it in your project, you need to refer to it from the Project Reference. To begin, go to the Solution Explorer of Visual Studio Project. Right-click on Reference and then select Add Reference, search for the namespace System.Runtime.Caching and add it. See the images below for more:

In-memory Cache Tutorial in .NET

Add System.Runtime.Caching reference

In-memory Cache examples in .NET

System.Runtime.Caching reference added

After including the namespace System.Runtime.Caching, your application can use MemoryCache features for creating and adding cache easily.

Next, developers can initialize the memory cache class and use it for their applications by writing the following .NET code:

var cache = new MemoryCache("demoCache");  

After initializing memory cache, we can add or store data in cache. For that, we will use the Add() method. There are three methods for adding data to the cache. Below we can see one way to add cache in our applications:

bool Add(CacheItem item, CacheItemPolicy policy)

In the above method, we can use two parameters. These are key and value parameters having an entry to the cache. After this, we initialize it and set the value.

Read: Intro to Azure Redis Cache

How to Add Data in the CacheItem Object

The following example demonstrates how to add data in the CacheItem object:

var cacheItem = new CacheItem("MyName", "Tapas Pal");  

The CacheItem parameter means a newly added entry for a cache. The second parameter uses CacheItemPolicy, which means that, after our cache data is removed, some other features are available.

Refer to the following example to see how to initialize the cacheItemPolicy class and add a time value to store the data in the cache.

var cacheItemPolicy = new CacheItemPolicy  
{  
    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(120.0)  
};
var result = cache.Add(cacheItem, cacheItemPolicy);  

The above cache.Add() method will return a true or false value. True means that it added data successfully to the cache and false means it was unsuccessful.

Refer to the following overloaded method of cache add(). The first parameter is the key of the cache entry. The second parameter is the value of the cache entry. The third parameter is the CacheItemPolicy of the cache entry.

bool Add(string key, object value, CacheItemPolicy policy) 

The following cache Set() method is available too:

void Set(CacheItem item, CacheItemPolicy policy)

The first parameter cache item class initializes and stores the key and value data and the second parameter CacheItemPolicy class initializes and sets the expiration time and other settings.

Next, to retrieve data from the cache, developers can use the following Get() method:

object Get(string key)

This will return the value that we stored in the cache. Here is an example of how to get data from a memory cache:

var value = cache.Get("FullName");  

Next, to remove any data from the cache, a developer can use the Remove() method, as shown here:

object Remove(string key)

The following example shows how to remove a key from the cache:

var result = cache.Remove("FullName");  

Finally, the following code snippets will add an item in cache and print the cache values:

 
cache.Add(new CacheItem("MyFirstName", "Tapas"), cacheItemPolicy);  
cache.Add(new CacheItem("MyLastName", "Pal"), cacheItemPolicy);  
var result = cache.GetValues(new string[] { "MyFirstName", " MyLastName", " MyFullName" });  
foreach (var item in result)  
{  
    Console.WriteLine($"{item.Key} : {item.Value}");  
}  

Conclusion to Implementing In-memory Caching in .NET

This article explains how to add and read data from in-memory cache in .NET. Remember, in-memory cache is used when the application is hosted on a single server.

Read more .NET programming tutorials.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read