Memory Cache in C#

Introduction

Today, we all are learning about the cache implementation of our web application.

Nowadays, we have many problems related to the performance of applications. Therefore, we have an option for data used mostly in your application. This data is stored in the cache. Afterward, when you have to use the data on your application side, first we need to fetch the data in the cache. If not available, then we have to update the cache data so then we can find that data. This increases performance in our application.

Make sure that if you have used the memory cache, then you do not have more data to be added to the cache. If you have lot of data to be stored in the cache, then use another type of cache in your application.

Pros

  1. Reduce database call
  2. Reduce web service load
  3. Quickly find data instead of a database call

Cons

  1. Increased maintenance
  2. Scalability
  3. Sync with the database, if any data is changed or added then we have updated the cache data.

There are 3 types of cache available.

  1. In-Memory Cache
  2. Persistent in-process Cache
  3. Distributed Cache

In-Memory Cache

This is used for the short term. It's for when we have used data in our application or sometime after, you have to remove the cache data from our system, then we can use it.

Persistent in-process Cache

This is used for data outside of the cache, like if you saved the data in a file or database and then want to use it in our application.

Distributed Cache

This is used for a shared cache and multiple processes. We also use the same cache data as the Redis cache.

In-memory Cache

MemoryCache uses the namespace "System.Runtime.Caching"

If your application doesn't add a namespace, then please follow the below steps to add a namespace for caching.

  1. Go to the Solution Explorer
  2. Right-click on References and choose the 'Add reference' option
  3. Open the reference manager go to the Assemblies Tab and click on the framework
  4. Find the "System.Runtime.Caching". If not checked then please check that checkbox
  5. Click on the OK button, and after checking your application, it's added a reference.
    System runtime caching

Now we are initializing the memory cache class and using it for our application.

var cache = new MemoryCache("demoCache");

How do you add/store data in the cache?

We are using the Add method then in that added.

They have added three methods for adding data to the cache. Below we can see how to use it in our application.

bool Add(CacheItem item, CacheItemPolicy policy)

In that, we are used to two parameters.

The first parameter is used. CacheItem means the added entry for a cache. it's a key and value parameter so whenever we have any entry to the cache then we initialize this and set the data.

Here is an example of how we have added data in the cache item object.

var cacheItem = new CacheItem("fullName", "Jaimin Shethiya");

The second parameter uses CacheItemPolicy, which means after our cache data is removed some other features are available. For example, when the data is removed after we have an operation performed, then they have added a callback function so we have to again set the data or any other operation.

Here's an example of how to initialize the cache item policy class and add a time to store the data in the cache.

var cacheItemPolicy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0)
};

Lastly, we stored the data in our cache.

var result = cache.Add(cacheItem, cacheItemPolicy);

It will return a true or false. True means that it added data successfully to the cache and false means that it added data unsuccessfully to the cache.

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

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 cache item policy of the cache entry.

Here is an example of how to add data to the memory cache.

var result = cache.Add("fullName", "Jaimin Shethiya", cacheItemPolicy);

It will return a true or false, true means added data successfully to the cache, and false means added data unsuccessfully to the cache.

bool Add(string key, object value, DateTimeOffset absoluteExpiration)

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 expiry of the time we have stored the data in the cache.

Here is an example of how to add data to the memory cache.

var result = cache.Add("fullName", "Jaimin Shethiya", DateTimeOffset.Now.AddMinutes(10));

It will return a true or false. True means it added data successfully to the cache and false means it added data unsuccessfully to the cache.

Also, the set method is available for added/stored data in the memory cache.

The same approach is available for the Add method we have learned.

void Set(CacheItem item, CacheItemPolicy policy)

The first parameter cache item class initializes and stores the key and value data.

The second parameter cache item policy class initializes and sets the expiration time and other settings.

Here is an example of how to set data in the memory cache.

cache.Set(cacheItem, cacheItemPolicy);

void Set(string key, object value, CacheItemPolicy policy)

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 cache item policy of the cache entry.

Here is an example of how to set data in the memory cache.

cache.Set("fullName", "Jaimin Shethiya", cacheItemPolicy);

void Set(string key, object value, DateTimeOffset absoluteExpiration)

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 expiry of the time we have stored the data in the cache.

Here is an example of how to set data in the memory cache.

cache.Set("fullName", "Jaimin Shethiya", DateTimeOffset.Now.AddMinutes(10));

Contains

This is used for whether the key is already added to the cache or not.

Syntax

bool Contains(string key)

Here is an example of how to check contained data in the memory cache.

var isExists = cache.Contains("fullName");

It will return a true or false, true means exist the key to the cache and false means not exist the key in the cache.

How to retrieve the data from the cache?

object Get(string key)

It will return a value that we have stored in the cache. if not getting any result then also do not throw any error but they have returned as a null value.

Here is an example of how to get data from a memory cache.

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

Return the full name we have stored in the memory cache "Jaimin Shethiya"

CacheItem GetCacheItem(string key)

It will return a cache item class whatever we have stored in the memory cache.

Here is an example of how to get a cache item from the memory cache.

var result = cache.GetCacheItem("fullName");
Console.WriteLine("fullName {0}", result.Value);

GetCount

It will return the number of the count whatever we have stored the data in the memory cache.

Here is an example of how to get a count from the memory cache.

var result = cache.GetCount("fullName");
Console.WriteLine("total {0}", result);

Remove

It will help remove any data from the cache and return that key value if exists otherwise return a null value.

Syntax

object Remove(string key)

Here is an example of how to remove any key from the cache.

var result = cache.Remove("fullName");
Console.WriteLine("fullName {0}", result);

GetValues

It will return multiple values from the object.

Syntax

IDictionary<string, object> GetValues(IEnumerable<string> keys)

Here is an example.

cache.Add(cacheItem, cacheItemPolicy);
cache.Add(new CacheItem("firstName", "Jaimin"), cacheItemPolicy);
cache.Add(new CacheItem("lastName", "Shethiya"), cacheItemPolicy);
var result = cache.GetValues(new string[] { "firstName", "lastName", "fullName" });
foreach (var item in result)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}

Details

Add or get existing data from the cache.

CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy)

If already added, then it will return data in the cache item class but the value is a null return.

Here is an example

var item = cache.AddOrGetExisting(new CacheItem("middleName", "Ashwinbhai"), cacheItemPolicy);
Console.WriteLine(item.Value);

Var item

Another example is the already added key in the cache and again added. Then it will return as a cache item data with all the values.

Here is the example.

var item = cache.AddOrGetExisting(cacheItem, cacheItemPolicy);
Console.WriteLine(item.Value);

 Cache memory

Happy coding, enjoy coding!!!


Similar Articles