Example #1
0
        /// <inheritdoc/>
        public TValue GetOrAdd(TKey key, Func <TKey, TValue> valueFactory)
        {
            TValue value;

            using (_lock.Read())
            {
                if (_values.TryGetValue(key, out value))
                {
                    return(value);
                }
            }

            var newValue = valueFactory(key);

            using (_lock.Write())
            {
                if (_values.TryGetValue(key, out value))
                {
                    return(value);
                }

                _values.Add(key, newValue);
            }

            return(value);
        }
Example #2
0
        /// <inheritdoc/>
        public TValue GetOrAdd(TKey key, Func <TKey, TValue> valueFactory)
        {
            TValue value;

            using (_lock.UpgradeableRead())
            {
                if (_values.TryGetValue(key, out value))
                {
                    return(value);
                }

                using (_lock.Write())
                {
                    if (_values.TryGetValue(key, out value))
                    {
                        return(value);
                    }

                    value = valueFactory(key);
                    _values.Add(key, value);
                }
            }

            return(value);
        }