Last active
August 29, 2015 14:08
-
-
Save ctigeek/5e653d6650d1d2d8a4a9 to your computer and use it in GitHub Desktop.
Generic .net cache....
This file contains hidden or 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
| class Cache<T> where T : someBaseType | |
| { | |
| public readonly TimeSpan LifeSpan; | |
| public readonly SemaphoreSlim semaphore; | |
| private Dictionary<string, CacheItem<T>> itemDict; | |
| public Cache(TimeSpan lifespan) | |
| { | |
| this.LifeSpan = lifespan; | |
| itemDict = new Dictionary<string, CacheItem<T>>(); | |
| semaphore = new SemaphoreSlim(1, 1); | |
| } | |
| //you can have async methods as well... semaphore.WaitAsync() | |
| public T Save(T item) | |
| { | |
| try | |
| { | |
| semaphore.Wait(); | |
| itemDict[item.UniqueId] = new CacheItem<T>(item); | |
| return item; | |
| } | |
| finally | |
| { | |
| semaphore.Release(); | |
| } | |
| } | |
| public T Invalidate(T item) | |
| { | |
| try | |
| { | |
| semaphore.Wait(); | |
| if (itemDict.ContainsKey(item.UniqueId)) itemDict.Remove(item.UniqueId); | |
| return item; | |
| } | |
| finally | |
| { | |
| semaphore.Release(); | |
| } | |
| } | |
| public T Fetch(T item) | |
| { | |
| try | |
| { | |
| semaphore.Wait(); | |
| if (itemDict.ContainsKey(item.UniqueId)) | |
| { | |
| var cacheItem = itemDict[item.UniqueId]; | |
| if (DateTime.Now.Subtract(cacheItem.Created) > LifeSpan) | |
| { | |
| itemDict.Remove(item.UniqueId); | |
| return null; | |
| } | |
| return cacheItem.Item; | |
| } | |
| return null; | |
| } | |
| finally | |
| { | |
| semaphore.Release(); | |
| } | |
| } | |
| } | |
| class CacheItem<T> where T : someBaseType | |
| { | |
| public readonly DateTime Created; | |
| public readonly T Item; | |
| public CacheItem(T item) | |
| { | |
| this.Item = item; | |
| this.Created = DateTime.Now; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment