public bool AddToCache(TV cacheKey, TU value) { var cachedResult = new CacheDataObject <TU> { Usage = 1, //value == null ? 1 : value.Usage + 1, Value = value, Timestamp = DateTime.UtcNow }; _cache.AddOrUpdate(cacheKey, cachedResult, (_, __) => cachedResult); if (_cache.Count > MaxSize) { foreach (var source in _cache .OrderByDescending(x => x.Value.Usage) .ThenBy(x => x.Value.Timestamp) .Skip(MaxSize - CleanSize)) { if (EqualityComparer <TV> .Default.Equals(source.Key, cacheKey)) { continue; // we don't want to remove the one we just added } CacheDataObject <TU> ignored; _cache.TryRemove(source.Key, out ignored); } } return(true); }
public bool AddToCache(TV cacheKey, TU value) { var cachedResult = new CacheDataObject <TU> { Usage = 1, Value = value, Timestamp = DateTime.UtcNow }; _cache.AddOrUpdate(cacheKey, cachedResult, (_, __) => cachedResult); if (_cache.Count > 0 && _cache.Count > CacheMaxSize && !IsCleaning) { lock (_lockObject) { if (IsCleaning) { return(true); } try { IsCleaning = true; var cacheArray = _cache.ToArray(); if (cacheArray.Length > 0) { var itemsToSkip = CacheMaxSize - CleanSize; if (itemsToSkip > 10) { var items = cacheArray.OrderByDescending(x => x.Value.Usage) .ThenBy(x => x.Value.Timestamp) .Skip(itemsToSkip); if (items.Any()) { foreach (var source in items) { if (source.Key == null || cacheKey == null) { continue; } if (EqualityComparer <TV> .Default.Equals(source.Key, cacheKey)) { continue; // we don't want to remove the one we just added } CacheDataObject <TU> ignored; _cache.TryRemove(source.Key, out ignored); } } } } } finally { IsCleaning = false; } } } return(true); }