Skip to content

Instantly share code, notes, and snippets.

@snmslavk
Created March 16, 2016 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snmslavk/af490fb954817efd016d to your computer and use it in GitHub Desktop.
Save snmslavk/af490fb954817efd016d to your computer and use it in GitHub Desktop.
Custom Synchronized Cache
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace TestCustomCache
{
public sealed class CacheSingleton
{
private static readonly SynchronizedCache instance = new SynchronizedCache();
static CacheSingleton()
{
}
private CacheSingleton()
{
}
public static SynchronizedCache Instance
{
get
{
return instance;
}
}
}
public class SynchronizedCache
{
private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
private Dictionary<string, string> innerCache = new Dictionary<string, string>();
public int Count
{ get { return innerCache.Count; } }
public string Read(string key)
{
cacheLock.EnterReadLock();
try
{
string result = null;
innerCache.TryGetValue(key, out result);
return result;
}
finally
{
cacheLock.ExitReadLock();
}
}
public void Add(string key, string value)
{
cacheLock.EnterWriteLock();
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
}
~SynchronizedCache()
{
if (cacheLock != null) cacheLock.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment