Ejemplo n.º 1
0
        /// <summary>
        ///     Tries to insert a cache entry into the cache as a <see cref="T:System.Runtime.Caching.CacheItem" /> instance,
        ///     and adds details about how the entry should be evicted.
        /// </summary>
        /// <returns>
        ///     true if insertion succeeded, or false if there is an already an entry in the cache that has the same key as
        ///     <paramref name="item" />.
        /// </returns>
        /// <param name="item">The object to add.</param>
        /// <param name="policy">
        ///     An object that contains eviction details for the cache entry. This object provides more options
        ///     for eviction than a simple absolute expiration.
        /// </param>
        public override bool Add(CacheItem item, CacheItemPolicy policy)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (policy == null)
            {
                throw new ArgumentNullException(nameof(policy));
            }

            var cacheRegion = this.AddOrGetExistingCacheRegion(item);

            if (cacheRegion.ContainsKey(item.Key))
            {
                return(false);
            }

            var entryItem = new CacheEntryItem(item, policy);

            cacheRegion.Add(item.Key, entryItem);

            this.ValidatePolicy(entryItem);

            return(true);
        }
Ejemplo n.º 2
0
        private void ValidatePolicy(CacheEntryItem item)
        {
            if (DateTime.Now - item.LastAccessed < item.SlidingExpiration &&
                item.Expiration.Ticks - DateTime.Now.Ticks > 0)
            {
                item.LastAccessed = DateTime.Now;
                return;
            }

            item.EntryRemovedCallback(
                new CacheEntryRemovedArguments(this, CacheEntryRemovedReason.Expired, item.ToCacheItem()));
            this.InternalCache[item.RegionName].Remove(item.Key);
        }