SaintModeCache


A thread safe caching implementation for performance optimisation

Usage

quick start

The following guide shows how to get up and running with SaintModeCache.Net as quicky as possible.

Installation

To install SaintModeCache.Net, run the following command in the Package Manager Console.

PM> Install-Package SaintModeCache.Net

GetOrCreate

First the SaintModeCache needs a static reference to the instance in order to persist data in memory.

static SaintModeCache Cache = new SaintModeCache();

Use the instance GetOrCreate method to retrieve the object from cache, or synchronously create if it does not exist. This method ensures that only one thread performs the fetch during a cache miss.

var cacheKey = "customer123"; 
var cacheTimeInSeconds = 60; 
var customerModel = Cache.GetOrCreate(cacheKey,
                   (key, cancelToken) => slowUnreliableService.GetCustomerModel(key),
                   cacheTimeInSeconds);

UpdateCacheCancellationToken

Use UpdateCacheCancellationToken to cancel an update if the cache update delegate fails. In this case the next cache miss will trigger a retry and callers will continue using stale data.

var cache = new SaintModeCache(); 
var cacheKey = "customer123"; 
var cacheTimeInSeconds = 60; 

// initalise a fallback cache item in case of cancel
cache.SetOrUpdateWithoutCreate(cacheKey, DataModel.Default, cacheTimeInSeconds);

// continues to return the previously set cache item, even after it expirie
var cachedValue = cache.GetOrCreate(cacheKey, (key,cancelToken) => { 
        // on failure to get data from remote resources
        cancelToken.IsCancellationRequested = true;
        return null; 
    }, 
    cacheTimeInSeconds); 

Cancelling the UpdateCacheCancellationToken can result in a null response from GetOrCreate. This happens when UpdateCacheCancellationToken is used and the cache is empty. It’s therefore recommended not to cancel updates, but instead provide a default value where possible.

var cache = new SaintModeCache(); 
var cacheKey = "customer123"; 
var cacheTimeInSeconds = 60; 

// initalise a fallback cache item in case of cancel
cache.SetOrUpdateWithoutCreate(cacheKey, DataModel.Default, cacheTimeInSeconds);

// continues to return the previously set cache item, even after it expirie
var cachedValue = cache.GetOrCreate(cacheKey, (key,cancelToken) => { 
        // on failure to get data from remote resources
        return new DefaultCustomer(); 
    }, 
    cacheTimeInSeconds);