Exemple #1
0
        /// <summary>
        /// Attempts to get a value from cache.
        /// If it is found in cache, return true, and the value.
        /// If it is not found in cache, return false, and use the valueFactory callback to generate and return the value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="valueFactory">A callback that can create the value.</param>
        /// <returns>
        /// True if the value came from cache, otherwise false.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">valueFactory</exception>
        public bool TryGetOrAdd(TKey key, out TValue value, Func <TKey, TValue> valueFactory)
        {
            if (valueFactory == null)
            {
                throw new ArgumentNullException(nameof(valueFactory));
            }

            Func <TKey, LastAccessedEntry> factory = k =>
            {
                TValue val = valueFactory(key);

                return(LastAccessedEntry.Create(val));
            };

            LastAccessedEntry lastAccessed;

            bool cameFromCache = _cache.TryGetOrAdd(key, out lastAccessed, factory);

            if (!cameFromCache)
            {
                IncrementCacheSize( );
            }
            else
            {
                lastAccessed.LastAccess = DateTime.UtcNow.Ticks;
            }

            value = lastAccessed.Value;

            return(cameFromCache);
        }
Exemple #2
0
        /// <summary>
        ///     Adds or updates the specified key/value pair.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <returns>
        ///     True if the specified key/value pair was added;
        ///     False if the specified key/value pair was updated.
        /// </returns>
        public bool Add(TKey key, TValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            bool added = _cache.Add(key, LastAccessedEntry.Create(value));

            if (added)
            {
                IncrementCacheSize( );
            }

            return(added);
        }