示例#1
0
        /// <inheritdoc />
        public void ClearOfType(string typeName)
        {
            var type = _typeFinder.GetTypeByName(typeName);

            if (type == null)
            {
                return;
            }
            var isInterface = type.IsInterface;

            foreach (var kvp in _items
                     .Where(x =>
            {
                // entry.Value is Lazy<object> and not null, its value may be null
                // remove null values as well, does not hurt
                // get non-created as NonCreatedValue & exceptions as null
                var value = SafeLazy.GetSafeLazyValue(x.Value, true);

                // if T is an interface remove anything that implements that interface
                // otherwise remove exact types (not inherited types)
                return(value == null || (isInterface ? (type.IsInstanceOfType(value)) : (value.GetType() == type)));
            }))
            {
                _items.TryRemove(kvp.Key, out _);
            }
        }
示例#2
0
        /// <inheritdoc />
        public object Get(string key, Func <object> factory, TimeSpan?timeout, bool isSliding = false, string[] dependentFiles = null)
        {
            // see notes in HttpRuntimeAppCache

            Lazy <object> result;

            using (var lck = new UpgradeableReadLock(_locker))
            {
                result = MemoryCache.Get(key) as Lazy <object>;
                if (result == null || SafeLazy.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null
                {
                    result = SafeLazy.GetSafeLazy(factory);
                    var policy = GetPolicy(timeout, isSliding, dependentFiles);

                    lck.UpgradeToWriteLock();
                    //NOTE: This does an add or update
                    MemoryCache.Set(key, result, policy);
                }
            }

            //return result.Value;

            var value = result.Value; // will not throw (safe lazy)

            if (value is SafeLazy.ExceptionHolder eh)
            {
                eh.Exception.Throw();                                       // throw once!
            }
            return(value);
        }
示例#3
0
        /// <inheritdoc />
        public void ClearOfType <T>(Func <string, T, bool> predicate)
        {
            var typeOfT     = typeof(T);
            var isInterface = typeOfT.IsInterface;

            foreach (var kvp in _items
                     .Where(x =>
            {
                // entry.Value is Lazy<object> and not null, its value may be null
                // remove null values as well, does not hurt
                // compare on exact type, don't use "is"
                // get non-created as NonCreatedValue & exceptions as null
                var value = SafeLazy.GetSafeLazyValue(x.Value, true);
                if (value == null)
                {
                    return(true);
                }

                // if T is an interface remove anything that implements that interface
                // otherwise remove exact types (not inherited types)
                return((isInterface ? (value is T) : (value.GetType() == typeOfT))
                       // run predicate on the 'public key' part only, ie without prefix
                       && predicate(x.Key, (T)value));
            }))
            {
                _items.TryRemove(kvp.Key, out _);
            }
        }
示例#4
0
        /// <inheritdoc />
        public virtual void ClearOfType <T>()
        {
            try
            {
                _locker.EnterWriteLock();
                var typeOfT     = typeof(T);
                var isInterface = typeOfT.IsInterface;
                foreach (var key in MemoryCache
                         .Where(x =>
                {
                    // x.Value is Lazy<object> and not null, its value may be null
                    // remove null values as well, does not hurt
                    // get non-created as NonCreatedValue & exceptions as null
                    var value = SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value, true);

                    // if T is an interface remove anything that implements that interface
                    // otherwise remove exact types (not inherited types)
                    return(value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT)));
                })
                         .Select(x => x.Key)
                         .ToArray()) // ToArray required to remove
                {
                    MemoryCache.Remove(key);
                }
            }
            finally
            {
                if (_locker.IsWriteLockHeld)
                {
                    _locker.ExitWriteLock();
                }
            }
        }
        /// <inheritdoc />
        public virtual void ClearOfType <T>()
        {
            var typeOfT     = typeof(T);
            var isInterface = typeOfT.IsInterface;

            try
            {
                EnterWriteLock();
                foreach (var entry in GetDictionaryEntries()
                         .Where(x =>
                {
                    // entry.Value is Lazy<object> and not null, its value may be null
                    // remove null values as well, does not hurt
                    // compare on exact type, don't use "is"
                    // get non-created as NonCreatedValue & exceptions as null
                    var value = SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value, true);

                    // if T is an interface remove anything that implements that interface
                    // otherwise remove exact types (not inherited types)
                    return(value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT)));
                })
                         .ToArray())
                {
                    RemoveEntry((string)entry.Key);
                }
            }
            finally
            {
                ExitWriteLock();
            }
        }
        /// <inheritdoc />
        public virtual void ClearOfType(string typeName)
        {
            var type = _typeFinder.GetTypeByName(typeName);

            if (type == null)
            {
                return;
            }
            var isInterface = type.IsInterface;

            try
            {
                EnterWriteLock();
                foreach (var entry in GetDictionaryEntries()
                         .Where(x =>
                {
                    // entry.Value is Lazy<object> and not null, its value may be null
                    // remove null values as well, does not hurt
                    // get non-created as NonCreatedValue & exceptions as null
                    var value = SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value, true);

                    // if T is an interface remove anything that implements that interface
                    // otherwise remove exact types (not inherited types)
                    return(value == null || (isInterface ? (type.IsInstanceOfType(value)) : (value.GetType() == type)));
                })
                         .ToArray())
                {
                    RemoveEntry((string)entry.Key);
                }
            }
            finally
            {
                ExitWriteLock();
            }
        }
示例#7
0
 /// <inheritdoc />
 public IEnumerable <object> SearchByKey(string keyStartsWith)
 {
     return(_items
            .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith))
            .Select(kvp => SafeLazy.GetSafeLazyValue(kvp.Value))
            .Where(x => x != null));
 }
示例#8
0
        /// <inheritdoc />
        public IEnumerable <object> SearchByRegex(string regex)
        {
            var compiled = new Regex(regex, RegexOptions.Compiled);

            return(_items
                   .Where(kvp => compiled.IsMatch(kvp.Key))
                   .Select(kvp => SafeLazy.GetSafeLazyValue(kvp.Value))
                   .Where(x => x != null));
        }
示例#9
0
 /// <inheritdoc />
 public void Insert(string key, Func <object> factory, TimeSpan?timeout = null, bool isSliding = false, string[] dependentFiles = null)
 {
     InnerCache.Insert(key, () =>
     {
         var result = SafeLazy.GetSafeLazy(factory);
         var value  = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache
         // do not store null values (backward compat), clone / reset to go into the cache
         return(value == null ? null : CheckCloneableAndTracksChanges(value));
     }, timeout, isSliding, dependentFiles);
 }
示例#10
0
        /// <inheritdoc />
        public object Get(string key, Func <object> factory)
        {
            var cached = InnerCache.Get(key, () =>
            {
                var result = SafeLazy.GetSafeLazy(factory);
                var value  = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache
                // do not store null values (backward compat), clone / reset to go into the cache
                return(value == null ? null : CheckCloneableAndTracksChanges(value));
            });

            return(CheckCloneableAndTracksChanges(cached));
        }
        /// <inheritdoc />
        public virtual object Get(string key)
        {
            key = GetCacheKey(key);
            Lazy <object> result;

            try
            {
                EnterReadLock();
                result = GetEntry(key) as Lazy <object>; // null if key not found
            }
            finally
            {
                ExitReadLock();
            }
            return(result == null ? null : SafeLazy.GetSafeLazyValue(result)); // return exceptions as null
        }
示例#12
0
        /// <inheritdoc />
        public override object Get(string key, Func <object> factory)
        {
            //no place to cache so just return the callback result
            if (!TryGetContextItems(out var items))
            {
                return(factory());
            }

            key = GetCacheKey(key);

            Lazy <object> result;

            try
            {
                EnterWriteLock();
                result = items[key] as Lazy <object>; // null if key not found

                // cannot create value within the lock, so if result.IsValueCreated is false, just
                // do nothing here - means that if creation throws, a race condition could cause
                // more than one thread to reach the return statement below and throw - accepted.

                if (result == null || SafeLazy.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null
                {
                    result     = SafeLazy.GetSafeLazy(factory);
                    items[key] = result;
                }
            }
            finally
            {
                ExitWriteLock();
            }

            // using GetSafeLazy and GetSafeLazyValue ensures that we don't cache
            // exceptions (but try again and again) and silently eat them - however at
            // some point we have to report them - so need to re-throw here

            // this does not throw anymore
            //return result.Value;

            var value = result.Value; // will not throw (safe lazy)

            if (value is SafeLazy.ExceptionHolder eh)
            {
                eh.Exception.Throw();                                       // throw once!
            }
            return(value);
        }
示例#13
0
        /// <inheritdoc />
        public void Insert(string key, Func <object> factory, TimeSpan?timeout = null, bool isSliding = false, string[] dependentFiles = null)
        {
            // NOTE - here also we must insert a Lazy<object> but we can evaluate it right now
            // and make sure we don't store a null value.

            var result = SafeLazy.GetSafeLazy(factory);
            var value  = result.Value; // force evaluation now

            if (value == null)
            {
                return;                // do not store null values (backward compat)
            }
            var policy = GetPolicy(timeout, isSliding, dependentFiles);

            //NOTE: This does an add or update
            MemoryCache.Set(key, result, policy);
        }
示例#14
0
        /// <inheritdoc />
        public object Get(string key)
        {
            Lazy <object> result;

            try
            {
                _locker.EnterReadLock();
                result = MemoryCache.Get(key) as Lazy <object>; // null if key not found
            }
            finally
            {
                if (_locker.IsReadLockHeld)
                {
                    _locker.ExitReadLock();
                }
            }
            return(result == null ? null : SafeLazy.GetSafeLazyValue(result)); // return exceptions as null
        }
示例#15
0
        /// <inheritdoc />
        public object Get(string cacheKey, Func <object> getCacheItem)
        {
            var result = _items.GetOrAdd(cacheKey, k => SafeLazy.GetSafeLazy(getCacheItem));

            var value = result.Value; // will not throw (safe lazy)

            if (!(value is SafeLazy.ExceptionHolder eh))
            {
                return(value);
            }

            // and... it's in the cache anyway - so contrary to other cache providers,
            // which would trick with GetSafeLazyValue, we need to remove by ourselves,
            // in order NOT to cache exceptions

            _items.TryRemove(cacheKey, out result);
            eh.Exception.Throw(); // throw once!
            return(null);         // never reached
        }
        /// <inheritdoc />
        public virtual IEnumerable <object> SearchByKey(string keyStartsWith)
        {
            var plen = CacheItemPrefix.Length + 1;
            IEnumerable <DictionaryEntry> entries;

            try
            {
                EnterReadLock();
                entries = GetDictionaryEntries()
                          .Where(x => ((string)x.Key).Substring(plen).InvariantStartsWith(keyStartsWith))
                          .ToArray(); // evaluate while locked
            }
            finally
            {
                ExitReadLock();
            }

            return(entries
                   .Select(x => SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value)) // return exceptions as null
                   .Where(x => x != null));                                        // backward compat, don't store null values in the cache
        }
示例#17
0
 /// <inheritdoc />
 public IEnumerable <object> SearchByKey(string keyStartsWith)
 {
     KeyValuePair <string, object>[] entries;
     try
     {
         _locker.EnterReadLock();
         entries = MemoryCache
                   .Where(x => x.Key.InvariantStartsWith(keyStartsWith))
                   .ToArray(); // evaluate while locked
     }
     finally
     {
         if (_locker.IsReadLockHeld)
         {
             _locker.ExitReadLock();
         }
     }
     return(entries
            .Select(x => SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value)) // return exceptions as null
            .Where(x => x != null)                                          // backward compat, don't store null values in the cache
            .ToList());
 }
        /// <inheritdoc />
        public virtual IEnumerable <object> SearchByRegex(string regex)
        {
            const string prefix   = CacheItemPrefix + "-";
            var          compiled = new Regex(regex, RegexOptions.Compiled);
            var          plen     = prefix.Length;
            IEnumerable <DictionaryEntry> entries;

            try
            {
                EnterReadLock();
                entries = GetDictionaryEntries()
                          .Where(x => compiled.IsMatch(((string)x.Key).Substring(plen)))
                          .ToArray(); // evaluate while locked
            }
            finally
            {
                ExitReadLock();
            }
            return(entries
                   .Select(x => SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value)) // return exceptions as null
                   .Where(x => x != null));                                        // backward compatible, don't store null values in the cache
        }
示例#19
0
        /// <inheritdoc />
        public void ClearOfType <T>()
        {
            var typeOfT     = typeof(T);
            var isInterface = typeOfT.IsInterface;

            foreach (var kvp in _items
                     .Where(x =>
            {
                // entry.Value is Lazy<object> and not null, its value may be null
                // remove null values as well, does not hurt
                // compare on exact type, don't use "is"
                // get non-created as NonCreatedValue & exceptions as null
                var value = SafeLazy.GetSafeLazyValue(x.Value, true);

                // if T is an interface remove anything that implements that interface
                // otherwise remove exact types (not inherited types)
                return(value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT)));
            }))
            {
                _items.TryRemove(kvp.Key, out _);
            }
        }
        /// <inheritdoc />
        public virtual void ClearOfType <T>(Func <string, T, bool> predicate)
        {
            var typeOfT     = typeof(T);
            var isInterface = typeOfT.IsInterface;
            var plen        = CacheItemPrefix.Length + 1;

            try
            {
                EnterWriteLock();
                foreach (var entry in GetDictionaryEntries()
                         .Where(x =>
                {
                    // entry.Value is Lazy<object> and not null, its value may be null
                    // remove null values as well, does not hurt
                    // compare on exact type, don't use "is"
                    // get non-created as NonCreatedValue & exceptions as null
                    var value = SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value, true);
                    if (value == null)
                    {
                        return(true);
                    }

                    // if T is an interface remove anything that implements that interface
                    // otherwise remove exact types (not inherited types)
                    return((isInterface ? (value is T) : (value.GetType() == typeOfT))
                           // run predicate on the 'public key' part only, ie without prefix
                           && predicate(((string)x.Key).Substring(plen), (T)value));
                }))
                {
                    RemoveEntry((string)entry.Key);
                }
            }
            finally
            {
                ExitWriteLock();
            }
        }
示例#21
0
        /// <inheritdoc />
        public IEnumerable <object> SearchByRegex(string regex)
        {
            var compiled = new Regex(regex, RegexOptions.Compiled);

            KeyValuePair <string, object>[] entries;
            try
            {
                _locker.EnterReadLock();
                entries = MemoryCache
                          .Where(x => compiled.IsMatch(x.Key))
                          .ToArray(); // evaluate while locked
            }
            finally
            {
                if (_locker.IsReadLockHeld)
                {
                    _locker.ExitReadLock();
                }
            }
            return(entries
                   .Select(x => SafeLazy.GetSafeLazyValue((Lazy <object>)x.Value)) // return exceptions as null
                   .Where(x => x != null)                                          // backward compat, don't store null values in the cache
                   .ToList());
        }
示例#22
0
 /// <inheritdoc />
 public object Get(string cacheKey)
 {
     _items.TryGetValue(cacheKey, out var result);                      // else null
     return(result == null ? null : SafeLazy.GetSafeLazyValue(result)); // return exceptions as null
 }