diff --git a/src/ImageProcessor.Web/Caching/MemCache.cs b/src/ImageProcessor.Web/Caching/MemCache.cs index 192a7b7b7..060a3e805 100644 --- a/src/ImageProcessor.Web/Caching/MemCache.cs +++ b/src/ImageProcessor.Web/Caching/MemCache.cs @@ -14,6 +14,9 @@ namespace ImageProcessor.Web.Caching using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.Caching; + using System.Threading; + + using ImageProcessor.Common.Helpers; /// /// Encapsulates methods that allow the caching and retrieval of objects from the in memory cache. @@ -25,6 +28,11 @@ namespace ImageProcessor.Web.Caching /// private static readonly ObjectCache Cache = MemoryCache.Default; + /// + /// The reader-writer lock implementation. + /// + private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); + /// /// An internal list of cache keys to allow bulk removal. /// @@ -56,8 +64,7 @@ namespace ImageProcessor.Web.Caching public static bool AddItem(string key, object value, CacheItemPolicy policy = null, string regionName = null) { bool isAdded; - - lock (Cache) + using (new WriteLock(Locker)) { if (policy == null) { @@ -100,7 +107,7 @@ namespace ImageProcessor.Web.Caching /// public static object GetItem(string key, string regionName = null) { - lock (Cache) + using (new UpgradeableReadLock(Locker)) { return Cache.Get(key, regionName); } @@ -173,7 +180,7 @@ namespace ImageProcessor.Web.Caching { bool isRemoved; - lock (Cache) + using (new WriteLock(Locker)) { isRemoved = Cache.Remove(key, regionName) != null; @@ -200,7 +207,7 @@ namespace ImageProcessor.Web.Caching { bool isCleared = false; - lock (CacheItems) + using (new WriteLock(Locker)) { // You can't remove items from a collection whilst you are iterating over it so you need to // create a collection to store the items to remove.