Click here to Skip to main content
15,887,746 members
Articles / Cache
Tip/Trick

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 7.7K   1   3
Caching doesn't have to be complicated.

Introduction

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 http://nuget.org.

Examples

Instantiation

JavaScript
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.

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

Adding to the Cache and Expiration

JavaScript
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

JavaScript
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.

JavaScript
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

JavaScript
cache.InvalidateCache();

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.

History

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

License

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 8:46
KevinAG1-Aug-17 8:46 
AnswerRe: System.Runtime.Caching.MemoryCache Pin
Sharp Ninja1-Aug-17 9:23
Sharp Ninja1-Aug-17 9:23 
GeneralRe: System.Runtime.Caching.MemoryCache Pin
KevinAG1-Aug-17 13:03
KevinAG1-Aug-17 13: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.