/// <summary> /// Add a new keyed object to the cache. /// </summary> /// <param name="key">The key of the object.</param> /// <param name="value">The object to add.</param> /// <param name="scavengingPriority">One of the <see cref="CacheItemPriority"/> values.</param> /// <param name="refreshAction">An <see cref="ICacheItemRefreshAction"/> object.</param> /// <param name="expirations">An array of <see cref="ICacheItemExpiration"/> objects.</param> public void Add(string key, object value, CacheItemPriority scavengingPriority,params ICacheItemExpiration[] expirations) { ValidateKey(key); CacheItem cacheItemBeforeLock = null; bool lockWasSuccessful = false; do { lock (inMemoryCache.SyncRoot) { if (inMemoryCache.Contains(key) == false) { cacheItemBeforeLock = new CacheItem(key, addInProgressFlag, CacheItemPriority.NotRemovable, null); inMemoryCache[key] = cacheItemBeforeLock; } else { cacheItemBeforeLock = (CacheItem)inMemoryCache[key]; } lockWasSuccessful = Monitor.TryEnter(cacheItemBeforeLock); } if (lockWasSuccessful == false) { Thread.Sleep(0); } } while (lockWasSuccessful == false); try { cacheItemBeforeLock.TouchedByUserAction(true); CacheItem newCacheItem = new CacheItem(key, value, scavengingPriority, expirations); try { //backingStore.Add(newCacheItem); cacheItemBeforeLock.Replace(value, scavengingPriority, expirations); inMemoryCache[key] = cacheItemBeforeLock; } catch { //backingStore.Remove(key); inMemoryCache.Remove(key); throw; } //instrumentationProvider.FireCacheUpdated(1, inMemoryCache.Count); } finally { Monitor.Exit(cacheItemBeforeLock); } }
private static bool IsObjectInCache(CacheItem cacheItemBeforeLock) { return cacheItemBeforeLock == null || Object.ReferenceEquals(cacheItemBeforeLock.Value, addInProgressFlag); }
private bool RemoveItemFromCache(CacheItem itemToRemove) { bool expired = false; lock (itemToRemove) { if (itemToRemove.WillBeExpired) { try { expired = true; cacheOperations.RemoveItemFromCache(itemToRemove.Key, CacheItemRemovedReason.Expired); } catch (Exception e) { //instrumentationProvider.FireCacheFailed(Resources.FailureToRemoveCacheItemInBackground, e); } } } return expired; }