Caching 3.1.1

dotnet add package Caching --version 3.1.1                
NuGet\Install-Package Caching -Version 3.1.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Caching" Version="3.1.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Caching --version 3.1.1                
#r "nuget: Caching, 3.1.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Caching as a Cake Addin
#addin nuget:?package=Caching&version=3.1.1

// Install Caching as a Cake Tool
#tool nuget:?package=Caching&version=3.1.1                

Caching

Simple, fast, effective FIFO and LRU Cache with events and persistence.

NuGet Version NuGet

This Caching library provides a simple implementation of a FIFO cache (first-in-first-out) and an LRU (least-recently-used) cache. It is written in C# and is designed to be thread-safe.

New in v3.1.x

  • Expiration attribute for cached entries
  • Minor refactor and bugfixes

Usage

Add reference to the Caching DLL and include the Caching namespace:

using Caching;

Initialize the desired cache:

class Person
{
  public string FirstName;
  public string LastName;
}

FIFOCache<string, Person> cache = new FIFOCache<string, Person>(capacity, evictCount);
LRUCache<string, Person> cache = new LRUCache<string, Person>(capacity, evictCount) 

// T1 is the type of the key
// T2 is the type of the value
// capacity (int) is the maximum number of entries
// evictCount (int) is the number to remove when the cache reaches capacity
// debug (boolean) enables console logging (use sparingly)

Add an item to the cache:

cache.AddReplace(key, data);
// key (T1) is a unique identifier
// data (T2) is whatever data you like

bool success = cache.TryAddReplace(key, data);
if (!success) { ... }

Add an item to the cache with expiration:

cache.AddReplace(key, data, DateTime.UtcNow.AddSeconds(10));
bool success = cache.TryAddReplace(key, data, DateTime.UtcNow.AddSeconds(10));

Get an item from the cache:

Person data = cache.Get(key);
// throws KeyNotFoundException if not present

if (!cache.TryGet(key, out data)) 
{ 
  // handle errors 
}
else 
{ 
  // use your data! 
}

Remove an item from the cache:

cache.Remove(key);

Other helpful methods:

T1 oldestKey = cache.Oldest();
T1 newestKey = cache.Newest();
int numEntries = cache.Count();
List<T1> keys = cache.GetKeys();
cache.Clear();

Retrieve all cached contents (while preserving the cache):

Dictionary<T1, T2> dump = cache.All();

Persistence

If you wish to include a persistence layer with the cache, i.e. to store and manage cached objects on another repository in addition to memory:

  1. Implement the IPersistenceDriver abstract class; refer to the Test.Persistence project for a sample implementation that uses a directory on the local hard drive
  2. Instantiate the cache (FIFOCache or LRUCache) and pass the instance of the IPersistenceDriver into the constructor
  3. If you wish to prepopulate the cache from the persistence driver, call .Prepopulate() before using the cache.
  4. If you clear the cache, the persistence layer will also be cleared.
// implementation of PersistenceDriver
public class MyPersistenceDriver : IPersistenceDriver
{
  public override void Delete(string key) { ... }
  public override void Clear() { ... }
  public override bool Exists(string key) { ... }
  public override byte[] Get(string key) { ... }
  public override void Write(string key, byte[] data) { ... }
  public override byte[] ToBytes(object data) { ... }
  public override T FromBytes<T>(byte[] data) { ... }
  public override List<string> Enumerate() { ... }
}

// instantiate the cache
MyPersistenceDriver persistence = new MyPersistenceDriver();
LRUCache<string, byte[]> cache = new LRUCache<string, byte[]>(capacity, evictCount, persistence);
cache.Prepopulate();

As objects are written to the cache, they are added to persistent storage through the Write method. When they are removed or evicted, they are eliminated via the Delete method. When the cache is cleared, the persistence layer is also cleared.

Events

If you wish to invoke events when certain cache actions are taken, attach event handlers to the entries found in FIFOCache.Events or LRUCache.Events. These events are invoked synchronously after the associated cache operation.

FIFOCache<string, byte[]> cache = new FIFOCache<string, byte[]>(_Capacity, _EvictCount);
cache.Events.Added += Added;
cache.Events.Cleared += Cleared;
cache.Events.Disposed += Disposed;
cache.Events.Evicted += Evicted;
cache.Events.Expired += Expired;
cache.Events.Prepopulated += Prepopulated;
cache.Events.Removed += Removed;
cache.Events.Replaced += Replaced;

static void Replaced(object sender, DataEventArgs<string, byte[]> e)
{
    Console.WriteLine("*** Cache entry " + e.Key + " replaced");
}

static void Removed(object sender, DataEventArgs<string, byte[]> e)
{
    Console.WriteLine("*** Cache entry " + e.Key + " removed");
}

static void Prepopulated(object sender, DataEventArgs<string, byte[]> e)
{
    Console.WriteLine("*** Cache entry " + e.Key + " prepopulated from persistent storage");
}

static void Evicted(object sender, List<string> e)
{
    Console.WriteLine("*** Eviction event involving " + e.Count + " entries");
    foreach (string curr in e) Console.WriteLine("    | " + curr);
}

static void Expired(object sender, string key)
{
    Console.WriteLine("*** Key " + key + " expired and removed from the cache");
}

static void Disposed(object sender, EventArgs e)
{
    Console.WriteLine("*** Disposed");
}

static void Cleared(object sender, EventArgs e)
{
    Console.WriteLine("*** Cache cleared");
}

static void Added(object sender, DataEventArgs<string, byte[]> e)
{
    Console.WriteLine("*** Cache entry " + e.Key + " added");
}

Version History

Refer to CHANGELOG.md for version history.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Caching:

Package Downloads
SimpleUdp

SimpleUdp is a super simple way of building UDP clients and servers in C#.

LiteGraph

LiteGraph is a simple graph database abstraction with a RESTful interface, JSON data query support, and GEXF output support.

View.Models

View.io is currently in BETA. Database models and supporting classes for View.io services.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.1.1 3,178 1/9/2024
3.1.0 134 12/26/2023
3.0.1 1,168 10/1/2023
3.0.0 1,885 8/1/2023
2.0.1 261 7/31/2023
2.0.0.4 3,187 2/24/2023
2.0.0.2 4,807 5/18/2022

More flexibility in persistence driver implementation, code cleanup