Created
March 16, 2016 08:16
-
-
Save snmslavk/af490fb954817efd016d to your computer and use it in GitHub Desktop.
Custom Synchronized Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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