MemoryCache – In-Memory Storage

MemoryCache Overview

 Working with a simple In-Memory Cache shouldn’t cause anyone a headache. It should be simple to use and implemented at the click of a button.

Enter MemoryCache, a very lightweight, thread safe In-Memory Cache ready to be used in scalable, multi-threaded solutions. MemoryCache is a .Net Library which can be installed directly from NuGet, making it quick and easy to store and retrieve objects.

MemoryCache: How To

So let’s get started. First off, Install MemoryCache through NuGet.

Congratulations

MemoryCache is now ready to use.

Store

To store an object, use the following;


Cache.Store("MyObjectKey", myObject);

An object can be stored with an expiration time (milliseconds) using;


Cache.Store("Key", object, 10000);

Update

To update the value of a cache item, whilst persisting any Expiration time set against it, use;


Cache.Update("key", "newValue");

Get

To gather an object, use the following;


var object = Cache.Get("MyObjectKey");

Get Multiple By Keys

To gather multiple objects by keys from MemoryCache, use the following;


Dictionary<string, object> result = Cache.GetMultiple(new List() { "KeyOne", "KeyTwo", "KeyThree"});

Get Multiple By Type

To collect all objects of a Type from MemoryCache, use the following;


Dictionary<string, object> result = Cache.GetMultiple();

Check Existence By Key

To check if an object exists by key within MemoryCache, use the following;


bool exists = Cache.Exists("MyKey");

Check Existence By Type

To check if any object exists of Type within MemoryCache, use the following;


bool exists = Cache.Exists();

Check Existence By Object

To check if an object already exists within MemoryCache, use the following;


bool exists = Cache.Exists(myObject);

Remove By Key

To remove an object from MemoryCache by Key, use the following;


Cache.Remove("MyKey");

Remove By Type

To remove all objects of Type from MemoryCache, use the following;


Cache.Remove();

Flush

To clear the MemoryCache, use the following;


Cache.Flush();

Count Cached Items

To count all items within the MemoryCache, use the following;


int itemCount = Cache.CacheCount();

Count Cached Items By Type

To count all items of Type within MemoryCache, use the following;


int itemCount = Cache.CacheCount<ObjectType>();

Maintenance

As of Version 1.1.0, MemoryCache contains a built-in maintenance system, which runs on a set interval. When run, any items in the cache that have been given an expiration will expire if that expiration interval has expired, this should be used to ensure items do not remain in the cache longer than intended.

By default, Maintenance is enabled and will run every 10 seconds. This can be changed using the methods found below.

The following methods are relevant to MemoryCache Maintenance;

Begin Maintenance

To enable Maintenance within MemoryCache (Enabled by Default), use the following command;

Cache.BeginMaintenance();
Cache.BeginMaintenance(1000); //Begin maintenance, setting the interval to one second

End Maintenance

To disable Maintenance within MemoryCache (Enabled by Default), use the following command;

Cache.EndMaintenance();

Set Maintenance Interval

To set the interval at which maintenance should be run;

Note -> The interval given is in milliseconds.


Cache.SetMaintenanceInterval(10000);

Add Expiration

To set the expiry of a cached object in MemoryCache;


Cache.AddExpiration("ObjectKey", 6000);  //Object will expire six seconds from now, but will remain in Cache until Maintenance next maintenance run after the 6 seconds

Remove Expiration

Removes an Expiration set against an object in the cache;


Cache.RemoveExpiration("MyKey");

Extend Expiration

An expiration time can be extended using;


Cache.ExtendExpiration("MyKey", 10000); //Extend by 10 seconds

Exceptions

Should MemoryCache take offense at an action, it will throw a MemoryCacheException.

The error message returned will explain what went wrong.

What To Expect In The Future.

I also plan to implement an expiry mechanism, with a maintenance task which will run to remove expired objects.

I also need to explore the differences in using ConcurrentDictionary over the current process of using an object lock for the cache to ensure thread safety, this could potentially become an update.

If you have any ideas, you can get in touch with me here.

Version History

Version 1.2.0 ->  Added overload to declare item expiration when storing. Added update method which persists object expiration. Added method to extend object expiration time.

Version 1.1.0 -> Added Automated Maintenance to MemoryCache

Version 1.0.1 -> Added missing .pdb file to NuGet Package (Dropped the ball on that one, 1.0.1 works!)

Version 1.0.0 -> Initial Release (Version does not work as .pdb is missing … Oops)