Skip to content

Instantly share code, notes, and snippets.

@nekman
Created December 8, 2011 14:36
Show Gist options
  • Save nekman/1447146 to your computer and use it in GitHub Desktop.
Save nekman/1447146 to your computer and use it in GitHub Desktop.
C# generic cache
using System;
using System.Collections.Generic;
namespace Cache
{
/// <summary>
/// Generic cache. Should be wrapped in a singelton.
/// - Some issues with reloading, see http://stackoverflow.com/questions/8403782/c-sharp-reload-singleton-cache/ for more info.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
public interface ICache<TKey, TValue>
{
/// <summary>
/// Gets or sets the <see cref="TValue"/> with the specified key.
/// </summary>
TValue this[TKey key] { get; set; }
/// <summary>
/// Gets all.
/// </summary>
/// <returns></returns>
ICollection<TValue> GetAll();
/// <summary>
/// Replace current items in cache with the new items.
/// </summary>
/// <param name="items">The cached items.</param>
void SetAll(IDictionary<TKey, TValue> items);
/// <summary>
/// Remove key and data from cache.
/// </summary>
void Remove(TKey key);
/// <summary>
/// Determines whether the specified key exists.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
bool ContainsKey(TKey key);
/// <summary>
/// Gets the number of elements contained in the <see cref="ICollection{TValue}"/>
/// </summary>
int Count { get; }
}
//Implementation of ICache
public class Cache<TKey, TValue> : ICache<TKey, TValue> where TKey : class
{
private readonly object _syncLock = new object();
private IDictionary<TKey, TValue> _internalCache = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
get
{
lock (_syncLock)
{
return !_internalCache.ContainsKey(key) ? default(TValue) : _internalCache[key];
}
}
set
{
lock (_syncLock)
{
_internalCache[key] = value;
}
}
}
public ICollection<TValue> GetAll()
{
lock (_syncLock)
{
return _internalCache.Values;
}
}
//TODO: Change input parameter to ICache
public void SetAll(IDictionary<TKey, TValue> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
var cache = new Dictionary<TKey, TValue>();
foreach (var item in items)
{
cache[item.Key] = item.Value;
}
lock (_syncLock)
{
_internalCache = cache;
}
}
public bool ContainsKey(TKey key)
{
if (key == null)
{
return false;
}
lock (_syncLock)
{
return _internalCache.ContainsKey(key);
}
}
public int Count
{
get
{
lock (_syncLock)
{
return _internalCache.Count;
}
}
}
public void Remove(TKey key)
{
lock (_syncLock)
{
_internalCache.Remove(key);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment