ICache<T>

OpenWaves.Caching abstracts caches behind ICache<T> interface. It is later used as a basis for implementing more advanced caching behaviors.

    public interface ICache<T> where T : class
    {
        void InsertValue(string key, T value, DateTime absoluteExpiration);
        void EvictValue(string key);
        T GetValue(string key);
    }

The interface is out of the box implemented by:
  • MemoryCacheWrapper - wrapper for MemoryCache
  • HttpCacheWrapper - wrapper for HttpContext.Current.Cache
  • DirectoryCache - simple cache implementation based on IDirectory<> useful for testing (WARNING: it does not track memory usage and can be source of serious memory leaks)
  • FileSystemCache - simple cache storing values in files - useful if you need cache that can survive app recycling (WARNING: currently it does not track space usage)

Below is a sample showing how MemoryCacheWrapper can be used as ICache<T> implementation.
Note how you can use InsertValue extension method to provide absolute expiration as time span rather than DateTime.

var cache = new MemoryCacheWrapper<string>(new MemoryCache("MyCache"))
cache.InsertValue("key1", "FirstValue", TimeSpan.FromHours(1));

IConcurrentCache<T>

IConcurrentCache abstracts a cache that can be accessed concurrently from multiple threads and ensures that when the value is not present in cache, only one thread will produce the value.

public interface IConcurrentCache<T> : ICache<T> where T : class
{
    T GetOrCreate(string key, Func<CacheEntry<T>> create);
}

Below is an example of how a concurrent cache can be used. If the value is not present in cache, it will be produced using provided function. The value produced will be cached for 1 hour.

IConcurrentCache<string> cache = ...;

var value = cache.GetOrCreate("key", 
    () => CacheEntry.FromValue(
        "it takes time to produce this value", 
        TimeSpan.FromHours(1)));

OpenWaves provides two implementations of IConcurrentCache interface.
  • ConcurrentCache is a wrapper for objects implementing ICache that provides synchronization of the priovided function in scope of a single key.
  • AsyncConcurrentCache is a wrapper for ICache that attempts to refresh expired cache entires asynchronously while it returns stale values.

Last edited Jul 31, 2012 at 10:48 AM by mgrzyb, version 3

Comments

No comments yet.