Пример #1
0
        /// <summary>
        /// Constructs a fully formed CacheItem. This constructor is to be used when restoring an existing
        /// CacheItem from the backing store. As such, it does not generate its own Guid for this instance,
        /// but allows the guid to be passed in, as read from the backing store.
        /// </summary>
        /// <param name="lastAccessedTime">Time this CacheItem last accessed by user.</param>
        /// <param name="key">Key provided  by the user for this cache item. May not be null.</param>
        /// <param name="value">Value to be stored. May be null.</param>
		/// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
        /// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
		/// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
        public CacheItem(DateTime lastAccessedTime, string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            Initialize(key, value, refreshAction, scavengingPriority, expirations);

            TouchedByUserAction(false, lastAccessedTime);
            InitializeExpirations();
        }
Пример #2
0
        /// <summary>
        /// 添加缓存文件依赖
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="itemRefreshFactory">缓存过期委托</param>
        public void AddFileDependency(string key, object value, string filePath, ICacheItemRefreshAction itemRefreshFactory)
        {
            ValidateOperator.Begin().CheckFileExists(filePath);
            FileDependency _fileDependency = new FileDependency(filePath);

            CacheManager.Add(key, value, CacheItemPriority.Normal, itemRefreshFactory, _fileDependency);
        }
Пример #3
0
 public RefreshActionData(ICacheItemRefreshAction refreshAction, string keyToRefresh, object removedData, CacheItemRemovedReason removalReason)
 {
     this.refreshAction = refreshAction;
     this.keyToRefresh = keyToRefresh;
     this.removalReason = removalReason;
     this.removedData = removedData;
 }
Пример #4
0
 public RefreshActionData(ICacheItemRefreshAction refreshAction, string keyToRefresh, object removedData, CacheItemRemovedReason removalReason)
 {
     this.refreshAction = refreshAction;
     this.keyToRefresh  = keyToRefresh;
     this.removalReason = removalReason;
     this.removedData   = removedData;
 }
Пример #5
0
        /// <summary>
        /// 依赖文件缓存(包含移除刷新事件)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="action"></param>
        /// <param name="dependFilePath"></param>
        public static void Add(string key, object value, ICacheItemRefreshAction action, string dependFilePath)
        {
            FileDependency depen = new FileDependency(dependFilePath);

            cache.Add(key, value, CacheItemPriority.Normal, action, depen);
            AddKey(key);
        }
Пример #6
0
 public RefreshActionData(ICacheItemRefreshAction refreshAction, string keyToRefresh, object removedData, CacheItemRemovedReason removalReason, CachingInstrumentationProvider instrumentationProvider)
 {
     this.refreshAction = refreshAction;
     this.keyToRefresh = keyToRefresh;
     this.removalReason = removalReason;
     this.removedData = removedData;
     this.instrumentationProvider = instrumentationProvider;
 }
Пример #7
0
 public RefreshActionData(ICacheItemRefreshAction refreshAction, string keyToRefresh, object removedData, CacheItemRemovedReason removalReason, ICachingInstrumentationProvider instrumentationProvider)
 {
     this.refreshAction           = refreshAction;
     this.keyToRefresh            = keyToRefresh;
     this.removalReason           = removalReason;
     this.removedData             = removedData;
     this.instrumentationProvider = instrumentationProvider;
 }
Пример #8
0
        /// <summary>
        /// 添加缓存项,有效时间: 从添加起持续N分钟后缓存失效
        /// </summary>
        /// <param name="key">缓存KEY</param>
        /// <param name="value">缓存对象</param>
        /// <param name="priority">缓存优先级</param>
        /// <param name="refreshAction">缓存项更新回调</param>
        /// <param name="duration">缓存有效时间(单位:分钟)</param>
        public void Add(string key, object value, CacheItemPriority priority, ICacheItemRefreshAction refreshAction, int duration)
        {
            if (Exists(key))
            {
                Remove(key);
            }

            cacheManager.Add(key, value, priority, refreshAction, new SlidingTime(TimeSpan.FromMinutes(duration)));
        }
Пример #9
0
        /// <summary>
        /// 添加缓存项,有效时间: 有效持续到指定时间
        /// </summary>
        /// <param name="key">缓存KEY</param>
        /// <param name="value">缓存对象</param>
        /// <param name="priority">缓存优先级</param>
        /// <param name="refreshAction">缓存项更新回调</param>
        /// <param name="absoluteTime">缓存有效时间</param>
        public void Add(string key, object value, CacheItemPriority priority, ICacheItemRefreshAction refreshAction, DateTime absoluteTime)
        {
            if (Exists(key))
            {
                Remove(key);
            }

            cacheManager.Add(key, value, priority, refreshAction, new AbsoluteTime(absoluteTime));
        }
Пример #10
0
        /// <summary>
        /// 添加缓存项,有效时间: 缓存依赖文件,文件发生变化时缓存失效
        /// </summary>
        /// <param name="key">缓存KEY</param>
        /// <param name="value">缓存对象</param>
        /// <param name="priority">缓存优先级</param>
        /// <param name="refreshAction">缓存项更新回调</param>
        /// <param name="filePath">缓存依赖文件</param>
        public void Add(string key, object value, CacheItemPriority priority, ICacheItemRefreshAction refreshAction, string filePath)
        {
            if (Exists(key))
            {
                Remove(key);
            }

            cacheManager.Add(key, value, priority, refreshAction, new FileDependency(filePath));
        }
Пример #11
0
 /// <summary>
 ///     Sets an object in cache using the specified key.
 ///     Allows the user to set some other options so that
 ///     they have better control of the cached items.
 /// </summary>
 /// <param name="key">The cache key.</param>
 /// <param name="value">The cache value.</param>
 /// <param name="scavengingPriority">The scavenging priority.</param>
 /// <param name="refreshAction">The refresh action.</param>
 /// <param name="expirations">The expirations.</param>
 /// <externalUnit cref="CacheManager"/>
 /// <externalUnit cref="CacheItemPriority"/>
 /// <externalUnit cref="ICacheItemRefreshAction"/>
 /// <externalUnit cref="ICacheItemExpiration"/>
 /// <revision revisor="dev06" date="10/6/2008" version="1.0.0.0">
 ///     Member created
 /// </revision>
 public static void Set(
     string key,
     object value,
     CacheItemPriority scavengingPriority,
     ICacheItemRefreshAction refreshAction,
     params ICacheItemExpiration[] expirations)
 {
     CacheManager.Instance.Cache.Add(
         key, value, scavengingPriority, refreshAction, expirations);
 }
Пример #12
0
 public KeyValuePair <Core.Tag, List <T> > AddTag <T>(Guid tagId, KeyValuePair <Core.Tag, List <T> > value,
                                                      ICacheItemRefreshAction cacheRefreshAction)
     where T : Core.Resource
 {
     if (_enableCaching)
     {
         _cacheManager.Add(GetTagKey <T>(tagId), value,
                           CacheItemPriority.High, cacheRefreshAction,
                           new AbsoluteTime(DateTime.Now.AddMinutes(_cacheExpirationTime)));
     }
     return(value);
 }
        public CacheItem Load()
        {
            string                  key   = (string)keyField.Read(false);
            object                  value = valueField.Read(true);
            CacheItemPriority       scavengingPriority = (CacheItemPriority)scavengingPriorityField.Read(false);
            ICacheItemRefreshAction refreshAction      = (ICacheItemRefreshAction)refreshActionField.Read(false);

            ICacheItemExpiration[] expirations = (ICacheItemExpiration[])expirationsField.Read(false);
            DateTime lastAccessedTime          = (DateTime)lastAccessedField.Read(false);

            return(new CacheItem(lastAccessedTime, key, value, scavengingPriority, refreshAction, expirations));
        }
Пример #14
0
 public KeyValuePair <Core.Person, List <T> > AddPerson <T>(Guid id, KeyValuePair <Core.Person, List <T> > value,
                                                            ICacheItemRefreshAction cacheRefreshAction)
     where T : Core.ScholarlyWork
 {
     if (_enableCaching)
     {
         _cacheManager.Add(GetAuthorKey <T>(id), value,
                           CacheItemPriority.High, cacheRefreshAction,
                           new AbsoluteTime(DateTime.Now.AddMinutes(_cacheExpirationTime)));
     }
     return(value);
 }
Пример #15
0
 public KeyValuePair <Core.Contact, List <T> > AddContributor <T>(Guid contributorId,
                                                                  KeyValuePair <Core.Contact, List <T> > value,
                                                                  ICacheItemRefreshAction cacheRefreshAction) where T : Core.ScholarlyWork
 {
     if (_enableCaching)
     {
         _cacheManager.Add(GetContributorKey <T>(contributorId), value,
                           CacheItemPriority.High, cacheRefreshAction,
                           new AbsoluteTime(DateTime.Now.AddMinutes(_cacheExpirationTime)));
     }
     return(value);
     //this.Add(GetContributorKey, contributorId, value, cacheRefreshAction);
 }
Пример #16
0
 /// <summary>
 /// 添加缓存
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <param name="cacheItemRefreshAction"></param>
 /// <param name="expiredSeconds"></param>
 /// <param name="isRefresh"></param>
 public static void Add(string key, object value, ICacheItemRefreshAction cacheItemRefreshAction, int expiredSeconds, bool isRefresh = false)
 {
     lock (locker)
     {
         if (isRefresh)
         {
             //自定义刷新方式,如果过期将自动重新加载,过期时间为5分钟
             cache.Add(key, value, CacheItemPriority.Normal, cacheItemRefreshAction, new AbsoluteTime(TimeSpan.FromSeconds(expiredSeconds)));
         }
         else
         {
             cache.Add(key, value);
         }
     }
 }
Пример #17
0
 private void Initialize(string key, object value, ICacheItemRefreshAction refreshAction, CacheItemPriority scavengingPriority, ICacheItemExpiration[] expirations)
 {
     this.key                = key;
     this.value              = value;
     this.refreshAction      = refreshAction;
     this.scavengingPriority = scavengingPriority;
     if (expirations == null)
     {
         this.expirations = new ICacheItemExpiration[1] {
             new NeverExpired()
         };
     }
     else
     {
         this.expirations = expirations;
     }
 }
Пример #18
0
 private void Initialize(string cacheItemKey, object cacheItemData, ICacheItemRefreshAction cacheItemRefreshAction, CacheItemPriority cacheItemPriority, ICacheItemExpiration[] cacheItemExpirations)
 {
     key                = cacheItemKey;
     data               = cacheItemData;
     refreshAction      = cacheItemRefreshAction;
     scavengingPriority = cacheItemPriority;
     if (cacheItemExpirations == null)
     {
         expirations = new ICacheItemExpiration[1] {
             new NeverExpired()
         };
     }
     else
     {
         expirations = cacheItemExpirations;
     }
 }
Пример #19
0
 /// <summary>
 /// Replaces the internals of the current cache item with the given new values. This is strictly used in the Cache
 /// class when adding a new item into the cache. By replacing the item's contents, rather than replacing the item
 /// itself, it allows us to keep a single reference in the cache, simplifying locking.
 /// </summary>
 /// <param name="value">Value to be stored. May be null.</param>
 /// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
 /// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
 /// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
 internal void Replace(object value, ICacheItemRefreshAction refreshAction, CacheItemPriority scavengingPriority, params ICacheItemExpiration[] expirations)
 {
     Initialize(this.key, value, refreshAction, scavengingPriority, expirations);
     TouchedByUserAction(false);
 }
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
 {
     throw new NotImplementedException();
 }
Пример #21
0
 /// <summary>
 /// Replaces the internals of the current cache item with the given new values. This is strictly used in the Cache
 /// class when adding a new item into the cache. By replacing the item's contents, rather than replacing the item
 /// itself, it allows us to keep a single reference in the cache, simplifying locking.
 /// </summary>
 /// <param name="value">Value to be stored. May be null.</param>
 /// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
 /// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
 /// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
 internal void Replace(object value, ICacheItemRefreshAction refreshAction, CacheItemPriority scavengingPriority, params ICacheItemExpiration[] expirations)
 {
     Initialize(this.key, value, refreshAction, scavengingPriority, expirations);
     TouchedByUserAction(false);
 }
Пример #22
0
 /// <summary>
 /// 添加绝对时间缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="absoluteTime">缓存过期绝对时间</param>
 /// <param name="itemRefreshFactory">缓存过期委托</param>
 public void AddAbsoluteTime(string key, object value, DateTime absoluteTime, ICacheItemRefreshAction itemRefreshFactory)
 {
     CacheManager.Add(key, value, CacheItemPriority.Normal, itemRefreshFactory, new AbsoluteTime(absoluteTime)
     {
     });
 }
Пример #23
0
 private void Initialize(string cacheItemKey, object cacheItemData, ICacheItemRefreshAction cacheItemRefreshAction, CacheItemPriority cacheItemPriority, ICacheItemExpiration[] cacheItemExpirations)
 {
     key = cacheItemKey;
     data = cacheItemData;
     refreshAction = cacheItemRefreshAction;
     scavengingPriority = cacheItemPriority;
     if (cacheItemExpirations == null)
     {
         expirations = new ICacheItemExpiration[1] {new NeverExpired()};
     }
     else
     {
         expirations = cacheItemExpirations;
     }
 }
Пример #24
0
 /// <summary>
 /// Replaces the internals of the current cache item with the given new values. This is strictly used in the Cache
 /// class when adding a new item into the cache. By replacing the item's contents, rather than replacing the item
 /// itself, it allows us to keep a single reference in the cache, simplifying locking.
 /// </summary>
 /// <param name="cacheItemData">Value to be stored. May be null.</param>
 /// <param name="cacheItemPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
 /// <param name="cacheItemRefreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
 /// <param name="cacheItemExpirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
 internal void Replace(object cacheItemData, ICacheItemRefreshAction cacheItemRefreshAction, CacheItemPriority cacheItemPriority, params ICacheItemExpiration[] cacheItemExpirations)
 {
     Initialize(this.key, cacheItemData, cacheItemRefreshAction, cacheItemPriority, cacheItemExpirations);
     TouchedByUserAction(false);
 }
Пример #25
0
        /// <summary>
        /// Adds to cache
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="scavengingPriority"></param>
        /// <param name="refreshAction"></param>
        /// <param name="expirations"></param>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            if (String.IsNullOrEmpty(key))
            {
                return;
            }

            key = DnaHasher.GenerateHashString(key);
            using (new Tracer(this.GetType().ToString()))
            {
                if (expirations == null || expirations.Length == 0)
                {
                    _mc.Set(key, value);
                }
                else
                {
                    DateTime expiry = DateTime.Now.AddDays(1);
                    foreach (ICacheItemExpiration item in expirations)
                    {
                        switch (item.GetType().Name.ToString().ToUpper())
                        {
                            case "ABSOLUTETIME":
                                expiry = ((AbsoluteTime)item).AbsoluteExpirationTime;
                                break;

                            case "NEVEREXPIRED":
                                expiry = DateTime.Now.AddYears(1);
                                break;

                            case "SLIDINGTIME":
                                expiry = DateTime.Now.Add(((SlidingTime)item).ItemSlidingExpiration);
                                break;
                        }
                    }

                    int tries = 20;
                    bool setSuccess = false;
                    while (!setSuccess && tries > 0)
                    {
                        setSuccess = _mc.Set(key, value, expiry);
                        if (!setSuccess)
                        {
                            if (_mc.LastError != null && _mc.LastError.IndexOf("object too large for cache") >= 0)
                            {
                                return;
                            }
                        }
                        tries--;
                    }

                    //failed to set
                    if (!setSuccess)
                    {
                        Logger.Write(new LogEntry() { Message = "Failed to set in memcached", Severity = System.Diagnostics.TraceEventType.Error });
                        DnaDiagnostics.Default.WriteWarningToLog("CACHING", _mc.LastError);
                    }

                    LastCachedOjectSize = _mc.CachedObjectSize;
                }

            }
        }
Пример #26
0
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            ValidateKey(key);
            EnsureCacheInitialized();

            CacheItem cacheItemBeforeLock = null;
            bool      lockWasSuccessful   = false;

            do
            {
                lock (inMemoryCache.SyncRoot)
                {
                    if (inMemoryCache.Contains(key) == false)
                    {
                        cacheItemBeforeLock = new CacheItem(key, addInProgressFlag, CacheItemPriority.NotRemovable, null);
                        inMemoryCache[key]  = cacheItemBeforeLock;
                    }
                    else
                    {
                        cacheItemBeforeLock = (CacheItem)inMemoryCache[key];
                    }

                    lockWasSuccessful = Monitor.TryEnter(cacheItemBeforeLock);
                }

                if (lockWasSuccessful == false)
                {
                    Thread.Sleep(0);
                }
            } while (lockWasSuccessful == false);

            try
            {
                cacheItemBeforeLock.TouchedByUserAction(true);

                CacheItem newCacheItem = new CacheItem(key, value, scavengingPriority, refreshAction, expirations);
                try
                {
                    backingStore.Add(newCacheItem);
                    cacheItemBeforeLock.Replace(value, refreshAction, scavengingPriority, expirations);
                    inMemoryCache[key] = cacheItemBeforeLock;
                }
                catch
                {
                    backingStore.Remove(key);
                    inMemoryCache.Remove(key);
                    throw;
                }

                if (scavengingPolicy.IsScavengingNeeded(inMemoryCache.Count))
                {
                    cacheScavenger.StartScavenging();
                }

                CachingServiceItemTurnoverEvent.FireAddItems(1);
                CachingServiceItemTurnoverEvent.SetItemsTotal(inMemoryCache.Count);
            }
            finally
            {
                Monitor.Exit(cacheItemBeforeLock);
            }
        }
Пример #27
0
 /// <summary>
 /// 添加滑动过期缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="slidingTime">滑动过期时间</param>
 /// <param name="itemRefreshFactory">缓存过期委托</param>
 public void AddSlidingTime(string key, object value, TimeSpan slidingTime, ICacheItemRefreshAction itemRefreshFactory)
 {
     CacheManager.Add(key, value, CacheItemPriority.Normal, itemRefreshFactory, new SlidingTime(slidingTime)
     {
     });
 }
Пример #28
0
        /// <summary>
        /// Constructs a fully formed CacheItem.
        /// </summary>
        /// <param name="key">Key identifying this CacheItem</param>
        /// <param name="value">Value to be stored. May be null.</param>
        /// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
        /// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
        /// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
        public CacheItem(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            Initialize(key, value, refreshAction, scavengingPriority, expirations);

            TouchedByUserAction(false);
        }
Пример #29
0
 private void Initialize(string cacheItemKey, object cacheItemData, ICacheItemRefreshAction cacheItemRefreshAction, CacheItemPriority cacheItemPriority, ICacheItemExpiration[] cacheItemExpirations)
 {
     key = cacheItemKey;
     data = cacheItemData;
     refreshAction = cacheItemRefreshAction;
     ScavengingPriority = cacheItemPriority;
     expirations = cacheItemExpirations ?? new ICacheItemExpiration[] { new NeverExpired() };
 }
Пример #30
0
        /// <summary>
        /// Adds new CacheItem to cache. If another item already exists with the same key, that item is removed before
        /// the new item is added. If any failure occurs during this process, the cache will not contain the item being added.
        /// </summary>
        /// <param name="key">Identifier for this CacheItem</param>
        /// <param name="value">Value to be stored in cache. May be null.</param>
        /// <param name="scavengingPriority">Specifies the new item's scavenging priority.
        /// See <see cref="CacheItemPriority"/> for more information.</param>
        /// <param name="refreshAction">Object provided to allow the cache to refresh a cache item that has been expired. May be null.</param>
        /// <param name="expirations">Param array specifying the expiration policies to be applied to this item. May be null or omitted.</param>
        /// <exception cref="ArgumentNullException">Provided key is null</exception>
        /// <exception cref="ArgumentException">Provided key is an empty string</exception>
        /// <remarks>The CacheManager can be configured to use different storage mechanisms in which to store the CacheItems.
        /// Each of these storage mechanisms can throw exceptions particular to their own implementations.</remarks>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            System.Runtime.Caching.CacheItemPriority cacheItemPriority = System.Runtime.Caching.CacheItemPriority.Default;

            switch (scavengingPriority)
            {
                case CacheItemPriority.Normal:
                    cacheItemPriority = System.Runtime.Caching.CacheItemPriority.Default;
                    break;
                case CacheItemPriority.None:
                case CacheItemPriority.Low:
                case CacheItemPriority.NotRemovable:
                    cacheItemPriority = System.Runtime.Caching.CacheItemPriority.NotRemovable;
                    break;
            }

            DateTime absoluteExpiration = DateTime.Now.AddMinutes(Settings.Default.CacheAbsoluteExpirationMinutes);
            TimeSpan slidingExpiration = TimeSpan.Zero;

            if (expirations != null)
            {
                foreach (var expiration in expirations)
                {
                    if (expiration.GetType().IsOfType<AbsoluteTime>())
                    {
                        absoluteExpiration = ((AbsoluteTime)expiration).ExpirationTime;
                    }
                    else if (expiration.GetType().IsOfType<NeverExpired>())
                    {
                        absoluteExpiration = DateTime.MaxValue;
                    }
                    else if (expiration.GetType().IsOfType<SlidingTime>())
                    {
                        slidingExpiration = ((SlidingTime)expiration).SlidingExpiration;
                    }
                }
            }

            Cache.Add(key, value, new CacheItemPolicy
            {
                AbsoluteExpiration = absoluteExpiration,
                SlidingExpiration = slidingExpiration,
                Priority = cacheItemPriority,
                RemovedCallback = args =>
                {
                    CacheItemRemovedReason removalReason = CacheItemRemovedReason.Unknown;
                    switch (args.RemovedReason)
                    {
                        case System.Runtime.Caching.CacheEntryRemovedReason.ChangeMonitorChanged:
                            removalReason = CacheItemRemovedReason.DependencyChanged;
                            break;
                        case System.Runtime.Caching.CacheEntryRemovedReason.Expired:
                            removalReason = CacheItemRemovedReason.Expired;
                            break;
                        case System.Runtime.Caching.CacheEntryRemovedReason.Evicted:
                            removalReason = CacheItemRemovedReason.Scavenged;
                            break;
                    }
                    if (refreshAction != null)
                        refreshAction.Refresh(args.CacheItem.Key, args.CacheItem.Value, removalReason);
                }

            });
        }
Пример #31
0
 private void Initialize(string key, object value, ICacheItemRefreshAction refreshAction, CacheItemPriority scavengingPriority, ICacheItemExpiration[] expirations)
 {
     this.key = key;
     this.value = value;
     this.refreshAction = refreshAction;
     this.scavengingPriority = scavengingPriority;
     if (expirations == null)
     {
         this.expirations = new ICacheItemExpiration[1] {new NeverExpired()};
     }
     else
     {
         this.expirations = expirations;
     }
 }
Пример #32
0
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            ValidateKey(key);
            EnsureCacheInitialized();

            CacheItem cacheItemBeforeLock = null;
            bool lockWasSuccessful = false;

            do
            {
                lock (inMemoryCache.SyncRoot)
                {
                    if (inMemoryCache.Contains(key) == false)
                    {
                        cacheItemBeforeLock = new CacheItem(key, addInProgressFlag, CacheItemPriority.NotRemovable, null);
                        inMemoryCache[key] = cacheItemBeforeLock;
                    }
                    else
                    {
                        cacheItemBeforeLock = (CacheItem)inMemoryCache[key];
                    }

                    lockWasSuccessful = Monitor.TryEnter(cacheItemBeforeLock);
                }

                if (lockWasSuccessful == false)
                {
                    Thread.Sleep(0);
                }
            } while (lockWasSuccessful == false);

            try
            {
                cacheItemBeforeLock.TouchedByUserAction(true);

                CacheItem newCacheItem = new CacheItem(key, value, scavengingPriority, refreshAction, expirations);
                try
                {
                    backingStore.Add(newCacheItem);
                    cacheItemBeforeLock.Replace(value, refreshAction, scavengingPriority, expirations);
                    inMemoryCache[key] = cacheItemBeforeLock;
                }
                catch
                {
                    backingStore.Remove(key);
                    inMemoryCache.Remove(key);
                    throw;
                }

                if (scavengingPolicy.IsScavengingNeeded(inMemoryCache.Count))
                {
                    cacheScavenger.StartScavenging();
                }

                CachingServiceItemTurnoverEvent.FireAddItems(1);
                CachingServiceItemTurnoverEvent.SetItemsTotal(inMemoryCache.Count);
            }
            finally
            {
                Monitor.Exit(cacheItemBeforeLock);
            }
        }
		/// <summary>
		/// Adds new CacheItem to cache. If another item already exists with the same key, that item is removed before
		/// the new item is added. If any failure occurs during this process, the cache will not contain the item being added.
		/// </summary>
		/// <param name="key">Identifier for this CacheItem</param>
		/// <param name="value">Value to be stored in cache. May be null.</param>
		/// <param name="scavengingPriority">Specifies the new item's scavenging priority. 
		/// See <see cref="CacheItemPriority" /> for more information.</param>
		/// <param name="refreshAction">Object provided to allow the cache to refresh a cache item that has been expired. May be null.</param>
		/// <param name="expirations">Param array specifying the expiration policies to be applied to this item. May be null or omitted.</param>
		/// <exception cref="ArgumentNullException">Provided key is null</exception>
		/// <exception cref="ArgumentException">Provided key is an empty string</exception>
		/// <remarks>The CacheManager can be configured to use different storage mechanisms in which to store the CacheItems.
		/// Each of these storage mechanisms can throw exceptions particular to their own implementations.</remarks>
		public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
		{
			realCache.Add(key, value, scavengingPriority, refreshAction, expirations);
            
            backgroundScheduler.StartScavengingIfNeeded();
		}
Пример #34
0
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Adds new CacheItem to cache. If another item already exists with the same key, that item is removed before
        /// the new item is added. If any failure occurs during this process, the cache will not contain the item being added.
        /// </summary>
        /// <param name="key">Identifier for this CacheItem</param>
        /// <param name="value">Value to be stored in cache. May be null.</param>
        /// <param name="scavengingPriority">Specifies the new item's scavenging priority.
        /// See <see cref="CacheItemPriority" /> for more information.</param>
        /// <param name="refreshAction">Object provided to allow the cache to refresh a cache item that has been expired. May be null.</param>
        /// <param name="expirations">Param array specifying the expiration policies to be applied to this item. May be null or omitted.</param>
        /// <exception cref="ArgumentNullException">Provided key is null</exception>
        /// <exception cref="ArgumentException">Provided key is an empty string</exception>
        /// <remarks>The CacheManager can be configured to use different storage mechanisms in which to store the CacheItems.
        /// Each of these storage mechanisms can throw exceptions particular to their own implementations.</remarks>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            realCache.Add(key, value, scavengingPriority, refreshAction, expirations);

            backgroundScheduler.StartScavengingIfNeeded();
        }
Пример #36
0
        /// <summary>
        /// Constructs a fully formed CacheItem. This constructor is to be used when restoring an existing
        /// CacheItem from the backing store. As such, it does not generate its own Guid for this instance,
        /// but allows the GUID to be passed in, as read from the backing store.
        /// </summary>
        /// <param name="lastAccessedTime">Time this CacheItem last accessed by user.</param>
        /// <param name="key">Key provided  by the user for this cache item. May not be null.</param>
        /// <param name="value">Value to be stored. May be null.</param>
        /// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
        /// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
        /// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
        public CacheItem(DateTime lastAccessedTime, string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            Initialize(key, value, refreshAction, scavengingPriority, expirations);

            TouchedByUserAction(false, lastAccessedTime);
            InitializeExpirations();
        }
Пример #37
0
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations);
Пример #38
0
 /// <summary>
 /// 添加特定的格式来过期缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="extendedFormatString">过期时间</param>
 /// <param name="itemRefreshFactory">缓存过期委托</param>
 public void AddExtendedFormatTime(string key, object value, string extendedFormatString, ICacheItemRefreshAction itemRefreshFactory)
 {
     cacheMgr.Add(key, value, CacheItemPriority.Normal, itemRefreshFactory, new ExtendedFormatTime(extendedFormatString)
     {
     });
 }
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
 {
     
     primitivesCache.Add(key, value, scavengingPriority, refreshAction, expirations);
 }
Пример #40
0
        /// <summary>
        /// Constructs a fully formed CacheItem. 
        /// </summary>
        /// <param name="key">Key identifying this CacheItem</param>
        /// <param name="value">Value to be stored. May be null.</param>
		/// <param name="scavengingPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
		/// <param name="refreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
		/// <param name="expirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
        public CacheItem(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            Initialize(key, value, refreshAction, scavengingPriority, expirations);

            TouchedByUserAction(false);
        }
 /// <summary>
 /// Adds an item to the cache
 /// </summary>
 /// <param name="key">Cache key</param>
 /// <param name="value">Value</param>
 /// <param name="scavengingPriority">CacheItemPriority</param>
 /// <param name="refreshAction">ICacheItemRefreshAction</param>
 /// <param name="expirations">ICacheItemExpirations</param>
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
 {
     // Do nothing
 }
Пример #42
0
        /// <summary>
        /// Replaces the internals of the current cache item with the given new values. This is strictly used in the Cache
        /// class when adding a new item into the cache. By replacing the item's contents, rather than replacing the item
        /// itself, it allows us to keep a single reference in the cache, simplifying locking.
        /// </summary>
		/// <param name="cacheItemData">Value to be stored. May be null.</param>
        /// <param name="cacheItemPriority">Scavenging priority of CacheItem. See <see cref="CacheItemPriority" /> for values.</param>
        /// <param name="cacheItemRefreshAction">Object supplied by caller that will be invoked upon expiration of the CacheItem. May be null.</param>
        /// <param name="cacheItemExpirations">Param array of ICacheItemExpiration objects. May provide 0 or more of these.</param>
        internal void Replace(object cacheItemData, ICacheItemRefreshAction cacheItemRefreshAction, CacheItemPriority cacheItemPriority, params ICacheItemExpiration[] cacheItemExpirations)
        {
            Initialize(this.key, cacheItemData, cacheItemRefreshAction, cacheItemPriority, cacheItemExpirations);
            TouchedByUserAction(false);
        }
Пример #43
0
 public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
 {
     _storage.Add(key, value);
 }
Пример #44
0
 public static void StoreInCache(string key, object value, CacheItemPriority priority, ICacheItemRefreshAction action, ICacheItemExpiration[] expir)
 {
     if (null == value)
     {
         manager.Remove(key);
     }
     else
     {
         manager.Add(key, value, priority, action, expir);
     }
 }
        /// <summary>
        /// Add a new keyed object to the cache.
        /// </summary>
        /// <param name="key">The key of the object.</param>
        /// <param name="value">The object to add.</param>
        /// <param name="scavengingPriority">One of the <see cref="CacheItemPriority"/> values.</param>
        /// <param name="refreshAction">An <see cref="ICacheItemRefreshAction"/> object.</param>
        /// <param name="expirations">An array of <see cref="ICacheItemExpiration"/> objects.</param>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            ValidateKey(key);

            CacheItem cacheItemBeforeLock = null;
            bool      lockWasSuccessful   = false;

            do
            {
                lock (inMemoryCache.SyncRoot)
                {
                    if (inMemoryCache.Contains(key) == false)
                    {
                        cacheItemBeforeLock = new CacheItem(key, addInProgressFlag, CacheItemPriority.NotRemovable, null);
                        inMemoryCache[key]  = cacheItemBeforeLock;
                    }
                    else
                    {
                        cacheItemBeforeLock = (CacheItem)inMemoryCache[key];
                    }

                    lockWasSuccessful = Monitor.TryEnter(cacheItemBeforeLock);
                }

                if (lockWasSuccessful == false)
                {
                    Thread.Sleep(0);
                }
            } while (lockWasSuccessful == false);

            try
            {
                cacheItemBeforeLock.TouchedByUserAction(true);

                CacheItem newCacheItem = new CacheItem(key, value, scavengingPriority, refreshAction, expirations);
                try
                {
                    backingStore.Add(newCacheItem);
                    cacheItemBeforeLock.Replace(value, refreshAction, scavengingPriority, expirations);
                    inMemoryCache[key] = cacheItemBeforeLock;
                }
                catch
                {
                    backingStore.Remove(key);
                    inMemoryCache.Remove(key);
                    throw;
                }
                instrumentationProvider.FireCacheUpdated(1, inMemoryCache.Count);
            }
            finally
            {
                Monitor.Exit(cacheItemBeforeLock);
            }
        }
Пример #46
0
		/// <summary>
		/// Add a new keyed object to the cache.
		/// </summary>
		/// <param name="key">The key of the object.</param>
		/// <param name="value">The object to add.</param>
		/// <param name="scavengingPriority">One of the <see cref="CacheItemPriority"/> values.</param>
		/// <param name="refreshAction">An <see cref="ICacheItemRefreshAction"/> object.</param>
		/// <param name="expirations">An array of <see cref="ICacheItemExpiration"/> objects.</param>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            ValidateKey(key);

            CacheItem cacheItemBeforeLock = null;
            bool lockWasSuccessful = false;

            do
            {
                lock (inMemoryCache.SyncRoot)
                {
                    if (inMemoryCache.Contains(key) == false)
                    {
                        cacheItemBeforeLock = new CacheItem(key, addInProgressFlag, CacheItemPriority.NotRemovable, null);
                        inMemoryCache[key] = cacheItemBeforeLock;
                    }
                    else
                    {
                        cacheItemBeforeLock = (CacheItem)inMemoryCache[key];
                    }

                    lockWasSuccessful = Monitor.TryEnter(cacheItemBeforeLock);
                }

                if (lockWasSuccessful == false)
                {
                    Thread.Sleep(0);
                }
            } while (lockWasSuccessful == false);

            try
            {
                cacheItemBeforeLock.TouchedByUserAction(true);

                CacheItem newCacheItem = new CacheItem(key, value, scavengingPriority, refreshAction, expirations);
                try
                {
                    backingStore.Add(newCacheItem);
                    cacheItemBeforeLock.Replace(value, refreshAction, scavengingPriority, expirations);
                    inMemoryCache[key] = cacheItemBeforeLock;
                }
                catch
                {
                    backingStore.Remove(key);
                    inMemoryCache.Remove(key);
                    throw;
                }
				instrumentationProvider.FireCacheUpdated(1, inMemoryCache.Count);
            }
            finally
            {
                Monitor.Exit(cacheItemBeforeLock);
            }  
        
        }
Пример #47
0
        /// <summary>
        /// Adds new CacheItem to cache. If another item already exists with the same key, that item is removed before
        /// the new item is added. If any failure occurs during this process, the cache will not contain the item being added.
        /// </summary>
        /// <param name="key">Identifier for this CacheItem</param>
        /// <param name="value">Value to be stored in cache. May be null.</param>
        /// <param name="scavengingPriority">Specifies the new item's scavenging priority.
        /// See <see cref="CacheItemPriority"/> for more information.</param>
        /// <param name="refreshAction">Object provided to allow the cache to refresh a cache item that has been expired. May be null.</param>
        /// <param name="expirations">Param array specifying the expiration policies to be applied to this item. May be null or omitted.</param>
        /// <exception cref="ArgumentNullException">Provided key is null</exception>
        /// <exception cref="ArgumentException">Provided key is an empty string</exception>
        /// <remarks>The CacheManager can be configured to use different storage mechanisms in which to store the CacheItems.
        /// Each of these storage mechanisms can throw exceptions particular to their own implementations.</remarks>
        public void Add(string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration[] expirations)
        {
            System.Runtime.Caching.CacheItemPriority cacheItemPriority = System.Runtime.Caching.CacheItemPriority.Default;

            switch (scavengingPriority)
            {
            case CacheItemPriority.Normal:
                cacheItemPriority = System.Runtime.Caching.CacheItemPriority.Default;
                break;

            case CacheItemPriority.None:
            case CacheItemPriority.Low:
            case CacheItemPriority.NotRemovable:
                cacheItemPriority = System.Runtime.Caching.CacheItemPriority.NotRemovable;
                break;
            }

            DateTime absoluteExpiration = DateTime.Now.AddMinutes(Settings.Default.CacheAbsoluteExpirationMinutes);
            TimeSpan slidingExpiration  = TimeSpan.Zero;

            if (expirations != null)
            {
                foreach (var expiration in expirations)
                {
                    if (expiration.GetType().IsOfType <AbsoluteTime>())
                    {
                        absoluteExpiration = ((AbsoluteTime)expiration).ExpirationTime;
                    }
                    else if (expiration.GetType().IsOfType <NeverExpired>())
                    {
                        absoluteExpiration = DateTime.MaxValue;
                    }
                    else if (expiration.GetType().IsOfType <SlidingTime>())
                    {
                        slidingExpiration = ((SlidingTime)expiration).SlidingExpiration;
                    }
                }
            }

            Cache.Add(key, value, new CacheItemPolicy
            {
                AbsoluteExpiration = absoluteExpiration,
                SlidingExpiration  = slidingExpiration,
                Priority           = cacheItemPriority,
                RemovedCallback    = args =>
                {
                    CacheItemRemovedReason removalReason = CacheItemRemovedReason.Unknown;
                    switch (args.RemovedReason)
                    {
                    case System.Runtime.Caching.CacheEntryRemovedReason.ChangeMonitorChanged:
                        removalReason = CacheItemRemovedReason.DependencyChanged;
                        break;

                    case System.Runtime.Caching.CacheEntryRemovedReason.Expired:
                        removalReason = CacheItemRemovedReason.Expired;
                        break;

                    case System.Runtime.Caching.CacheEntryRemovedReason.Evicted:
                        removalReason = CacheItemRemovedReason.Scavenged;
                        break;
                    }
                    if (refreshAction != null)
                    {
                        refreshAction.Refresh(args.CacheItem.Key, args.CacheItem.Value, removalReason);
                    }
                }
            });
        }