コード例 #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, TimeoutEntry> callback = key1 =>
            {
                TValue newValue = valueFactory(key1);

                var newEntry = TimeoutEntry.Create(newValue);

                return(newEntry);
            };

            TimeoutEntry entry = null;

            bool isValid   = false;
            bool fromCache = false;

            while (!isValid)
            {
                fromCache = _cache.TryGetOrAdd(key, out entry, callback);

                /////
                // Check time stamp
                /////
                if (fromCache)
                {
                    isValid = IsValid(entry);

                    if (!isValid)
                    {
                        Remove(key);
                    }
                }
                else
                {
                    isValid = true;
                }
            }

            value = entry.Value;

            return(fromCache);
        }
コード例 #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)
 {
     return(_cache.Add(key, TimeoutEntry.Create(value)));
 }