Exemple #1
0
        /// <summary>
        /// 检查字典的容量。
        /// </summary>
        /// <param name="cacheKey">缓存键。</param>
        /// <param name="capacity">设定的容量值。</param>
        /// <param name="maxGen">当前最大的代。</param>
        /// <param name="onRemoved">移除的通知方法。</param>
        public void CheckCapacity(string cacheKey, int capacity, int maxGen, Action <CacheItem> onRemoved)
        {
            short gen = 0;

            while (Count > capacity && gen <= maxGen && gen < CacheOptimizer.MAX_GEN_LIMIT)
            {
                //查找出未创建值的,以及最小代或过期的,将它移除
                var needRemoveds = LazyValues.Where(s => s.Key != cacheKey &&
                                                    (!s.Value.IsValueCreated || s.Value.Value.Gen == gen || s.Value.Value.HasExpired())).ToArray();

                foreach (var item in needRemoveds)
                {
                    if (!item.Value.IsValueCreated)
                    {
                        LazyValues.TryRemove(item.Key, out Lazy <CacheItem> entry);
                    }
                    else if (TryRemove(item.Key, out CacheItem entry))
                    {
                        onRemoved(entry);
                    }
                }

                gen++;
            }
        }
Exemple #2
0
        internal Guid GetLazyLookupKeyValue(string lookupPropertyName)
        {
            var key = GetLazyLookupKey(lookupPropertyName);

            return(LazyValues.ContainsKey(key)
                                ? (Guid)LazyValues[key]
                                : Guid.Empty);
        }
Exemple #3
0
 /// <summary>
 /// 实例化 <see cref="SafetyDictionary{TKey, TValue}"/> 类的新实例。
 /// </summary>
 /// <param name="collection"></param>
 public SafetyDictionary(IEnumerable <KeyValuePair <TKey, TValue> > collection)
     : this()
 {
     if (collection != null)
     {
         foreach (var kvp in collection)
         {
             LazyValues.TryAdd(kvp.Key, new Lazy <TValue>(() => kvp.Value, _mode));
         }
     }
 }
Exemple #4
0
        internal void SetLazyLookupKeyValue(string lookupPropertyName, Guid value)
        {
            if (value == Guid.Empty)
            {
                return;
            }
            var key = GetLazyLookupKey(lookupPropertyName);

            if (LazyValues.ContainsKey(key))
            {
                LazyValues[key] = value;
            }
            else
            {
                LazyValues.Add(key, value);
            }
        }
Exemple #5
0
        /// <summary>
        /// 尝试通过 key 获取值,如果 key 不存在则通过函数生成新值并添加到字典中。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="valueFactory">新值的函数。</param>
        /// <returns></returns>
        public TValue GetOrAdd(TKey key, Func <TValue> valueFactory)
        {
            var lazy = LazyValues.GetOrAdd(key, k => new Lazy <TValue>(valueFactory, _mode));

            return(lazy != null && lazy.Value != null ? lazy.Value : default);