예제 #1
0
 public void OnExpiring()
 {
     if (!Expired)
     {
         Expiring?.Invoke(this, EventArgs.Empty);
         Expired = true;
     }
 }
예제 #2
0
        /// <summary>
        /// Remove item from cache by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="raiseEvents">Indicates whether events should be raised.</param>
        /// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param>
        /// <returns>The value indicating whether the item was removed.</returns>
        private bool RemoveItem(TKey key, bool raiseEvents, Action action = null)
        {
            // Try to get item, if there is no item by that key then return true to indicate that item was removed.
            var item = default(CacheStorageValueInfo <TValue>);

            if (!_dictionary.TryGetValue(key, out item))
            {
                return(true);
            }

            action?.Invoke();

            var cancel           = false;
            var expirationPolicy = item.ExpirationPolicy;

            if (raiseEvents)
            {
                var expiringEventArgs = new ExpiringEventArgs <TKey, TValue>(key, item.Value, expirationPolicy);
                Expiring.SafeInvoke(this, expiringEventArgs);

                cancel           = expiringEventArgs.Cancel;
                expirationPolicy = expiringEventArgs.ExpirationPolicy;
            }

            if (cancel)
            {
                if (expirationPolicy == null && _defaultExpirationPolicyInitCode != null)
                {
                    expirationPolicy = _defaultExpirationPolicyInitCode.Invoke();
                }

                _dictionary[key] = new CacheStorageValueInfo <TValue>(item.Value, expirationPolicy);

                return(false);
            }

            _dictionary.Remove(key);

            bool dispose = _disposeValuesOnRemoval;

            if (raiseEvents)
            {
                var expiredEventArgs = new ExpiredEventArgs <TKey, TValue>(key, item.Value, dispose);
                Expired.SafeInvoke(this, expiredEventArgs);

                dispose = expiredEventArgs.Dispose;
            }

            if (dispose)
            {
                item.DisposeValue();
            }

            return(true);
        }