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 performance of applications. Therefore, we have an option for data used mostly in your application. This data are stored to the cache. Afterwards, when you have to use the data in 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 to lots 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 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.
Basically, 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 some time 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 like 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 for added 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 and 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.
Memory Cache In C# 
 
Now we are initializing the memory cache class and using it for our application.
  1. var cache = new MemoryCache("demoCache");  
How to added/stored a data in 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 an 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.
  1. 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 the example of how to initialize the cache item policy class and added a time to store the data in the cache.
  1. var cacheItemPolicy = new CacheItemPolicy  
  2. {  
  3.     AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0)  
  4. };  
Lastly, we stored the data in our cache.
  1. 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 in the memory cache.
  1. var result = cache.Add("fullName""Jaimin Shethiya", cacheItemPolicy);  
It will return a true or false, true means added a data in successfully to the cache and false means added a data in 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 in the memory cache.
  1. 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.
  1. 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 a data in the memory cache:
  1. 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.
  1. cache.Set("fullName""Jaimin Shethiya", DateTimeOffset.Now.AddMinutes(10));  
Contains
 
This is used for whether the key is already added in the cache or not.
 
Syntax
 
bool Contains(string key)
 
Here is an example of how to check contained data in the memory cache.
  1. 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 whatever we have stored in the cache. if not getting any result then also 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.
  1. 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.
  1. var result = cache.GetCacheItem("fullName");  
  2. 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 the example of how to get a count from memory cache.
  1. var result = cache.GetCount("fullName");  
  2. 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 the example how to remove any key from the cache.
  1. var result = cache.Remove("fullName");  
  2. Console.WriteLine("fullName {0}", result);  
GetValues
 
It will return multiple values from the object.
 
Syntax
 
IDictionary<string, object> GetValues(IEnumerable<string> keys)
 
Here is the example.
  1. cache.Add(cacheItem, cacheItemPolicy);  
  2. cache.Add(new CacheItem("firstName""Jaimin"), cacheItemPolicy);  
  3. cache.Add(new CacheItem("lastName""Shethiya"), cacheItemPolicy);  
  4. var result = cache.GetValues(new string[] { "firstName""lastName""fullName" });  
  5.   
  6. foreach (var item in result)  
  7. {  
  8.     Console.WriteLine($"{item.Key} : {item.Value}");  
  9. }  
Memory Cache In C# 
 
Add or get existing data from the cache.
 
CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
 
If already added, then it will return a data in cache item class but the value as a null return.
 
Here is the example:
  1. var item = cache.AddOrGetExisting(new CacheItem("middleName""Ashwinbhai"), cacheItemPolicy);  
  2. Console.WriteLine(item.Value);  
Memory Cache In C#
 
Another example is the already added a key in the cache and again added. Then it will return as a cache item data with all the value.
 
Here is the example:
  1. var item = cache.AddOrGetExisting(cacheItem, cacheItemPolicy);  
  2. Console.WriteLine(item.Value);  
Memory Cache In C#
 
Happy coding, enjoy coding!!!