Exemple #1
0
        public void Set(string key, T item, TimeSpan?expiration = null, CacheUpdateCallback <T> expirationCallback = null)
        {
            _cache.AddOrUpdate(key, k =>
            {
                if (expiration.HasValue)
                {
                    _timers.Add(key, GetTimer(key, expiration.Value));

                    if (expirationCallback != null)
                    {
                        _callbacks.Add(key, expirationCallback);
                    }
                }

                return(item);
            },
                               (k, e) =>
            {
                if (_timers.ContainsKey(key))
                {
                    _timers[key].Stop();
                    if (!expiration.HasValue)
                    {
                        _timers.Remove(key);
                    }
                    else
                    {
                        _timers[key].Interval = expiration.Value.TotalMilliseconds;
                        _timers[key].Start();
                    }
                }
                else if (expiration.HasValue)
                {
                    _timers.Add(key, GetTimer(key, expiration.Value));
                }

                if (expirationCallback != null)
                {
                    _callbacks[key] = expirationCallback;
                }
                else if (_callbacks.ContainsKey(key))
                {
                    _callbacks.Remove(key);
                }

                return(item);
            });
        }
Exemple #2
0
        public T GetOrAdd(string key,
                          CacheUpdateCallback <T> getValueCallback,
                          TimeSpan?expiration = null,
                          CacheUpdateCallback <T> expirationCallback = null)
        {
            T item;

            // first try to get value from the cache
            if (_cache.TryGetValue(key, out item))
            {
                return(item);
            }
            // then try to get the value from the dedicated callback
            if (getValueCallback(out item))
            {
                Set(key, item, expiration, expirationCallback);
                return(item);
            }
            // if callback report failure avoid updating the cache
            return(item);
        }