private void Update(TKey key, KValue value, TimeSpan timeToExpiration, long size = 1) //Must be invoked inside a write lock { CacheItem <TKey, KValue> itemToBeUpdated = InternalCache.Single(it => it.Key.Equals(key)); if ((CurrentSize - itemToBeUpdated.Size + size) >= SizeLimit) { SizeLimitReached?.Invoke(this, EventArgs.Empty); FlushOutdatedItems(); } if ((CurrentSize + size) >= SizeLimit) { SizeLimitReached?.Invoke(this, EventArgs.Empty); FlushOldestItems(); } CurrentSize -= itemToBeUpdated.Size; itemToBeUpdated.Value = value; itemToBeUpdated.Expiration = timeToExpiration; itemToBeUpdated.Size = size; CurrentSize += itemToBeUpdated.Size; }
private async Task RemoveOutdatedAndOldestItems() { while (true) { Lock.EnterReadLock(); try { FlushOutdatedItems(); if (CurrentSize >= SizeLimit) { SizeLimitReached?.Invoke(this, EventArgs.Empty); FlushOldestItems(); } } catch (Exception ex) { throw new CacheOperationException(ex, CacheOperation.BackgroundThreadFlushItems); } finally { Lock.ExitReadLock(); } if (Token.IsCancellationRequested) { return; } await Task.Delay(PollingInterval, Token); } }
private void Add(TKey key, KValue value, TimeSpan timeToExpiration, long size = 1) //Must be invoked inside a write lock { if ((CurrentSize + size) >= SizeLimit) { SizeLimitReached?.Invoke(this, EventArgs.Empty); FlushOutdatedItems(); } if ((CurrentSize + size) >= SizeLimit) { SizeLimitReached?.Invoke(this, EventArgs.Empty); FlushOldestItems(); } CacheItem <TKey, KValue> itemToBeAdded = new CacheItem <TKey, KValue>(key, value, timeToExpiration, size); InternalCache.Add(itemToBeAdded); CurrentSize += itemToBeAdded.Size; }