Click here to Skip to main content
15,513,441 members
Articles / Cache
Posted 31 Jul 2017

Tagged as


1 bookmarked

SimpleCache Gives You a Small, Fast and Flexible Cache for Your Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
31 Jul 2017CPOL2 min read
Caching doesn't have to be complicated.


SimpleCache is the powerful cache that’s easy to use, yet fast and thread-safe! You can host SimpleCache in a Singleton in your app, or as a service in your n-Tier architecture. SimpleCache is scoped to CacheItem definitions based on the Key and Value types, allowing for high-speed data retrieval.

How Does It Work?

SimpleCache uses a ThreadSafeDictionary ConcurrentDictionary to hold its data. This dictionary allows for quick and easy, yet thread safe, access to the cache’s data. You can find the ThreadSafeDictionary in the GPS.SimpleThreading package on



var cache = new SimpleCache<Guid, string>(
    TimeSpan.FromMinutes(5.0), CacheExpirationTypes.Timed);

The first parameter on the constructor accepts the TimeSpan that defines how long a cache item can go unused before expiring. The second parameter defines the type of caching to use.

Timed caching starts a timer that fires every second. Any items that have not been accessed from the cache in the defined time period will be expunged from the cache and the ItemExpired event of the cache will be invoked for each expired item.

OnDemand caching does not start a timer, but instead the application is responsible for calling the ExpireCacheItems method of the cache. This method will check the current cache state for the expiration of any CacheItems.

The CacheItem

All data stored in the cache must be wrapped in a CacheItem. You and add data to the SimpleCache by adding new instances of CacheItem or by simply adding the key and value and the SimpleCache will create a CacheItem for you. The CacheItem will be used as a container that stores pertinent caching data such as the DateTimeOffset of the last access to the CacheItem through the cache itself only. Working with the CacheItem in your application does not update the last access, unless you change the data, which will trigger the NotifyPropertyChanged event that will tell the cache you have changed the data and will update the last access property.

var item = new CacheItem<int, record> 
    Key = 0,
    Value = myRec;

Adding to the Cache and Expiration

var cache = new SimpleCache<Guid, string>(
    TimeSpan.FromMinutes(2.5), CacheExpirationTypes.Timed);

cache.ItemExpired += (sender, item) =>
    // You expiration logic.  This is not required, it should
    // only be used if you need to ensure you always have fresh
    // data in the cache for your application.

cache.AddItem(new CacheItem<Guid, string> 
    { Key = Guid.Empty, Value = "example"});

Retrieving a CacheItem

var item = cache[key];
var value = item.Value;

When you access the item through the cache, it updates the last accessed property of the CacheItem, meaning that the sliding window for the expiration of the CacheItem is reset.

When you attempt to access a CacheItem, if it is expired, you will receive an ItemExpiredException. This allows you to watch for the exception and reload the data if necessary.

CacheItem<long, Tuple<string, string>> item;

try { item = cache[key];}
catch(ItemExpiredException iee)
    // Your data access here.
    cache.AddItem(new CacheItem<long, Tuple<string, string> 
        { Key = key, Value = data);

Invalidating the Cache


Invalidating the cache will remove all items from the cache. Attempts to access any removed cache item will result in the ItemExpiredException.

Where to Get SimpleCache

SimpleCache may be retrieved directly into your application through Nuget in Visual Studio. SimpleCache depends on GPS.SimpleThreading which will be pulled in as a dependency through Nuget.

The source code can be found on GitHub.


Version - Removed usages of ThreadSafeDictionary and ThreadSafeList and replaced with ConcurrentDictionary and ConcurrentBag.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionSystem.Runtime.Caching.MemoryCache Pin
KevinAG1-Aug-17 9:46
KevinAG1-Aug-17 9:46 
AnswerRe: System.Runtime.Caching.MemoryCache Pin
Sharp Ninja1-Aug-17 10:23
Sharp Ninja1-Aug-17 10:23 
The main difference is going to be that SimpleCache is type-safe. Also, the expiration mechanism on SimpleCache is, well, simpler.

For me, I want separate caches for objects of distinctly different types. I don't want great-big-huge-files in with itty-bitty-strings. This has performance implications a the MemoryCache can evict items based on on the size of incoming items. If you've got 2000 strings and someone dumps a 400mb file in there, then you may lose a bunch of those strings. Reloading say, 200 of those strings is expensive (or the cache wouldn't be necessary to begin with).

Since posting this Tip/Trick item, I've had a lot of revelations as to how improve the usage patterns without scope-creep. You'll see a new version of SimpleCache released this week.
GeneralRe: System.Runtime.Caching.MemoryCache Pin
KevinAG1-Aug-17 14:03
KevinAG1-Aug-17 14:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.