Пример #1
0
        public override async Task <T> IncrementField <T>(Expression <Func <T, bool> > filter, string field, int amount)
        {
            string cacheKey = typeof(T).Name;
            T      item     = default(T);
            await Task.Run(() =>
            {
                var list = _cacheManager.GetCachedData(new CacheItemArgs(cacheKey, ProviderLevel.High), (args) =>
                {
                    return(new List <T>());
                });
                var f = filter.Compile();
                lock (UniqueObject.GetUniqueObject <object>(cacheKey))
                {
                    item = list.Where(f).SingleOrDefault();
                    if (item != null)
                    {
                        var prop = item.GetType().GetProperty(field);
                        if (prop != null)
                        {
                            var propType = prop.PropertyType;

                            var val = (long)prop.GetValue(item) + amount;

                            var objVal = Convert.ChangeType(val, propType);
                            prop.SetValue(item, objVal);
                        }
                    }
                }
            });

            return(item);
        }
        public override void Clear(string scope = null)
        {
            var strScope = scope ?? _defaultScopeName;
            var ctsScope = UniqueObject.GetUniqueObject <CancellationTokenSource>(GetCacheKeyPrefix(strScope));

            ctsScope.Cancel();
        }
        public override void Insert(string cacheKey, object itemToCache, string scope = null, DateTimeOffset?absoluteExpiration = null, TimeSpan?slidingExpiration = null, FileCacheDependency dependency = null,
                                    RemoveDelegate onRemoveCallback = null)
        {
            var options = new MemoryCacheEntryOptions()
            {
                SlidingExpiration  = slidingExpiration,
                AbsoluteExpiration = absoluteExpiration
            };

            if (onRemoveCallback != null)
            {
                options.RegisterPostEvictionCallback((key, value, reason, state) =>
                {
                    onRemoveCallback(key, value, (RemoveReason)Enum.Parse(typeof(RemoveReason), reason.ToString()), state);
                });
            }

            if (dependency != null)
            {
                options.AddExpirationToken(dependency.GetChangeToken());
            }

            if (scope != null)
            {
                var ctsScope = UniqueObject.GetUniqueObject <CancellationTokenSource>(GetCacheKeyPrefix(scope));
                options.AddExpirationToken(new CancellationChangeToken(ctsScope.Token));
            }
            var ctsDefault = UniqueObject.GetUniqueObject <CancellationTokenSource>(GetCacheKeyPrefix(_defaultScopeName));

            options.AddExpirationToken(new CancellationChangeToken(ctsDefault.Token));

            string strKey = GetCacheKey(cacheKey, scope);

            _cache.Set(strKey, itemToCache, options);
        }
 private T SafeCreate <T>(string itemKey) where T : new()
 {
     lock (UniqueObject.GetUniqueObject <object>(itemKey))
     {
         object objValue = _cache.Get(itemKey);
         if (objValue == null)
         {
             var objItem = new T();
             this.Insert(itemKey, objItem);
             return(objItem);
         }
         return((T)objValue);
     }
 }
Пример #5
0
        public long DecrementValueInHash(string hashId, string key, int count, ProviderLevel level)
        {
            var provider = CachingProvider.Instance(level);

            if (!provider.IsDistributedCache())
            {
                object @lock = UniqueObject.GetUniqueObject <object>(key);
                lock (@lock)
                {
                    var retVal = provider.DecrementValueInHash(hashId, key, count);
                    UniqueObject.RemoveUniqueObject(key);
                    return(retVal);
                }
            }
            return(provider.DecrementValueInHash(hashId, key, count));
        }
Пример #6
0
        public long DecrementValue(string key, Func <long> initialCallBack, int count = 1, int expiredMinutes = 0, ProviderLevel level = ProviderLevel.Normal)
        {
            var provider = CachingProvider.Instance(level);

            if (!provider.IsDistributedCache())
            {
                object @lock = UniqueObject.GetUniqueObject <object>(key);
                lock (@lock)
                {
                    var retVal = provider.DecrementValue(key, count, expiredMinutes, initialCallBack);
                    UniqueObject.RemoveUniqueObject(key);
                    return(retVal);
                }
            }
            return(provider.DecrementValue(key, count, expiredMinutes, initialCallBack));
        }
Пример #7
0
        private TObject GetCachedDataInternal <TObject>(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback <TObject> cacheItemExpired)
        {
            TObject objObject = GetCache <TObject>(cacheItemArgs.CacheKey, cacheItemArgs.Scope, cacheItemArgs.Level);

            // if item is not cached
            if (EqualityComparer <TObject> .Default.Equals(objObject, default(TObject)))
            {
                //Get Unique Lock for cacheKey
                object @lock = UniqueObject.GetUniqueObject <object>(cacheItemArgs.CacheKey);

                // prevent other threads from entering this block while we regenerate the cache
                lock (@lock)
                {
                    // try to retrieve object from the cache again (in case another thread loaded the object since we first checked)
                    objObject = GetCache <TObject>(cacheItemArgs.CacheKey, cacheItemArgs.Scope, cacheItemArgs.Level);

                    // if object was still not retrieved

                    if (EqualityComparer <TObject> .Default.Equals(objObject, default(TObject)))
                    {
                        // get object from data source using delegate
                        //try
                        //{
                        objObject = cacheItemExpired(cacheItemArgs);
                        _logger.LogInformation("GetCacheItemFromExpiredCallback:" + cacheItemArgs.CacheKey);
                        //}
                        //catch (Exception ex)
                        //{
                        //     objObject = default(TObject);
                        //     _logger.LogError(ex, "CacheItemExpiredCallbackError");
                        // }

                        // if we retrieved a valid object and we are using caching
                        if (objObject != null)
                        {
                            // save the object in the cache
                            SetCache(cacheItemArgs.CacheKey,
                                     objObject,
                                     cacheItemArgs.Scope,
                                     cacheItemArgs.ExpireTimeOutMinutes > 0 ? DateTimeOffset.Now.AddMinutes(cacheItemArgs.ExpireTimeOutMinutes) : (DateTimeOffset?)null,
                                     cacheItemArgs.CacheTimeOutMinutes > 0 ? TimeSpan.FromMinutes(cacheItemArgs.CacheTimeOutMinutes) : (TimeSpan?)null,
                                     cacheItemArgs.Level,
                                     cacheItemArgs.CacheDependency,
                                     cacheItemArgs.CacheCallback);

                            // check if the item was actually saved in the cache

                            if (GetCache <TObject>(cacheItemArgs.CacheKey, cacheItemArgs.Scope, cacheItemArgs.Level) == null)
                            {
                                // log the event if the item was not saved in the cache ( likely because we are out of memory )
                                _logger.LogError("CACHE_OVERFLOW:" + cacheItemArgs.CacheKey + ":Overflow - Item Not Cached");
                            }
                        }

                        //This thread won so remove unique Lock from collection
                        UniqueObject.RemoveUniqueObject(cacheItemArgs.CacheKey);
                    }
                }
            }

            return(objObject);
        }