Пример #1
0
        public static MyMemoryCache CreateNew(CacheEntryRemovedCallback RemovedCallback)
        {
            var cache = new MyMemoryCache(Guid.NewGuid().ToString());

            cache.RemovedCallback = RemovedCallback;
            return(cache);
        }
Пример #2
0
        public String GetJsonFromCacheOrWebservice(string url)
        {
            String key = url;
            String ret = "";

            Logger.Trace("key=" + url + " IsCacheEnable=" + IsCacheEnable);
            if (IsCacheEnable)
            {
                ret = (String)MemoryCache.Default.Get(key);
                if (String.IsNullOrEmpty(ret))
                {
                    ret = MakeJsonRequest(url);

                    CacheItemPolicy           policy   = null;
                    CacheEntryRemovedCallback callback = null;
                    policy                    = new CacheItemPolicy();
                    policy.Priority           = CacheItemPriority.Default;
                    _callbackU                = new CacheEntryUpdateCallback(ContentCacheUpdateCallback);
                    policy.UpdateCallback     = _callbackU;
                    policy.AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheMinute);

                    MemoryCache.Default.Set(key, ret, policy);
                }
                else
                {
                    Logger.Trace("Get data from Cache=" + url);
                }
            }
            else
            {
                ret = MakeJsonRequest(url);
                Logger.Trace("Get data from API=" + url);
            }
            return(ret);
        }
Пример #3
0
        private static CacheItemPolicy BuildCachePolicy(
            DateTime?absoluteExpiration       = null,
            TimeSpan?slidingExpiration        = null,
            CacheEntryRemovedCallback removed = null,
            CacheEntryUpdateCallback updated  = null,
            ICacheDependency dependency       = null)
        {
            var policy = new CacheItemPolicy
            {
                Priority           = CacheItemPriority.Default,
                AbsoluteExpiration = absoluteExpiration.HasValue ? absoluteExpiration.Value : ObjectCache.InfiniteAbsoluteExpiration,
                SlidingExpiration  = slidingExpiration.HasValue ? slidingExpiration.Value : ObjectCache.NoSlidingExpiration,
                RemovedCallback    = removed,
                UpdateCallback     = updated
            };

            if (dependency != null)
            {
                var fileDependency = dependency as IFileCacheDependency;
                if (fileDependency != null)
                {
                    policy.ChangeMonitors.Add(new HostFileChangeMonitor(fileDependency.FilePaths));
                }
            }
            return(policy);
        }
Пример #4
0
        private void Add(string key, uint expireSeconds)
        {
#if NET45
            CacheItem                 item            = null;
            CacheItemPolicy           cip             = null;
            CacheEntryRemovedCallback removedCallback = null;
            _expireSeconds = expireSeconds;
            if (!_cache.Contains(key))
            {
                //实例化一个CacheItem缓存项
                item = new CacheItem(key, new object());
                //实例化CacheItemPolicy 并关联缓存项的一组逐出和过期详细信息
                cip                 = new CacheItemPolicy();
                removedCallback     = new CacheEntryRemovedCallback(CacheEntryRemovedCallbackProcess);
                cip.RemovedCallback = removedCallback;
                DateTime expire = DateTime.Now.AddSeconds(_expireSeconds);
                cip.AbsoluteExpiration = new DateTimeOffset(expire);
                //将缓存实例添加到系统缓存
                _cache.Add(item, cip);
            }
#elif NET35
            CacheItemRemovedCallback removedCallback = new CacheItemRemovedCallback(CacheItemRemovedCallbackProcess);
            _cache.Insert
            (
                key
                , new object()
                , null
                , Cache.NoAbsoluteExpiration
                , TimeSpan.FromSeconds(expireSeconds)
                , CacheItemPriority.Normal
                , removedCallback
            );
#endif
        }
Пример #5
0
        public static T GetCacheItem <T>(String key, Func <T> cachePopulate, CacheEntryRemovedCallback removedCallback, TimeSpan?slidingExpiration = null, DateTime?absoluteExpiration = null)
        {
            if (String.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Invalid cache key");
            }
            if (cachePopulate == null)
            {
                throw new ArgumentNullException("cachePopulate");
            }
            if (slidingExpiration == null && absoluteExpiration == null)
            {
                throw new ArgumentException("Either a sliding expiration or absolute must be provided");
            }

            if (MemoryCache.Default[key] == null)
            {
                lock (_locker)
                {
                    if (MemoryCache.Default[key] == null)
                    {
                        var item   = new CacheItem(key, cachePopulate());
                        var policy = CreatePolicy(slidingExpiration, absoluteExpiration, removedCallback);

                        MemoryCache.Default.Add(item, policy);
                    }
                }
            }

            return((T)MemoryCache.Default[key]);
        }
Пример #6
0
        public async Task GetOrAddAsyncWithCallbackOnRemovedReturnsTheOriginalCachedObjectEvenIfNotGettedBeforehand()
        {
            Func <Task <int> >         fetch = () => Task.FromResult(123);
            CacheEntryRemovedArguments removedCallbackArgs = null;
            CacheEntryRemovedCallback  callback            = args => removedCallbackArgs = args;
            await sut.GetOrAddAsync(TestKey, fetch,
                                    new CacheItemPolicy
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100),
                RemovedCallback    = callback
            });

            sut.Remove(TestKey); //force removed callback to fire
            while (removedCallbackArgs == null)
            {
                Thread.Sleep(500);
            }

            var callbackResult = removedCallbackArgs.CacheItem.Value;

            Assert.That(callbackResult, Is.AssignableTo <Task <int> >());
            var callbackResultValue = await(Task <int>) removedCallbackArgs.CacheItem.Value;

            Assert.AreEqual(123, callbackResultValue);
        }
    /// <summary>
    /// Store an object and let it stay in cache x minutes from write.
    /// callback is a method to be triggered when item is removed
    /// </summary>
    public static void SetAbsolute(string key, object data, double minutes, CacheEntryRemovedCallback callback, string domain = null)
    {
        CacheItemPolicy policy = new CacheItemPolicy {
            AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes), RemovedCallback = callback
        };

        Set(key, data, policy, domain);
    }
Пример #8
0
 /// <summary>
 /// 向缓存中设置缓存项
 /// </summary>
 /// <param name="key">该缓存项的唯一标识符。</param>
 /// <param name="value">要插入的对象。</param>
 /// <param name="minutesValue">分钟数,精确到最接近的毫秒。一个时段,必须在此时段内访问某个缓存项,否则将从内存中逐出该缓存项。</param>
 /// <param name="removedCallback">在从缓存中移除某个缓存项后将调用该方法。</param>
 public static void Set(string key, object value, double minutesValue, CacheEntryRemovedCallback RemovedCallback)
 {
     CacheItem item = new CacheItem(key, value);
     CacheItemPolicy policy = new CacheItemPolicy();
     policy.SlidingExpiration = TimeSpan.FromMinutes(minutesValue);
     policy.RemovedCallback = RemovedCallback;
     cache.Set(item, policy);
 }
Пример #9
0
 public LRUCache(int capacity)
 {
     _locker          = new ReaderWriterLockSlim();
     cache            = new MemoryCache(Guid.NewGuid().ToString());
     _capacity        = capacity > 0 ? capacity : DEFAULT_CAPACITY;
     _linkedList      = new LinkedList <CacheData>();
     removedCallback += AfterCacheRemove;
 }
Пример #10
0
        /// <summary>
        /// Adds or updates the serialized objects in the cache at the given cache keys.
        /// </summary>
        /// <param name="cacheKeysAndSerializedObjects">The cache keys and associated serialized objects.</param>
        /// <param name="tagName">The tag name.</param>
        /// <param name="absoluteExpiration">The absolute expiration. NOTE: if both absolute and sliding expiration are set, sliding expiration will be ignored.</param>
        /// <param name="slidingExpiration">The sliding expiration. NOTE: if both absolute and sliding expiration are set, sliding expiration will be ignored.</param>
        /// <param name="notifyRemoved">Whether or not to notify the client when the cached item is removed from the cache.</param>
        /// <param name="isInterned">Whether or not to intern the objects. NOTE: interned objects use significantly less memory when
        /// placed in the cache multiple times however cannot expire or be evicted. You must remove them manually when appropriate
        /// or else you will face a memory leak. If specified, absoluteExpiration, slidingExpiration, and notifyRemoved are ignored.</param>
        public void AddOrUpdate(IEnumerable <KeyValuePair <string, byte[]> > cacheKeysAndSerializedObjects, string tagName = null, DateTimeOffset?absoluteExpiration = null, TimeSpan?slidingExpiration = null, bool notifyRemoved = false, bool isInterned = false)
        {
            // Sanitize
            if (cacheKeysAndSerializedObjects == null)
            {
                throw new ArgumentNullException("cacheKeysAndSerializedObjects");
            }

            // Determine cache item policy
            CacheItemPolicy           cacheItemPolicy;
            CacheEntryRemovedCallback cacheEntryRemovedCallback = null;

            if (notifyRemoved)
            {
                cacheItemPolicy           = _defaultRemovedCallbackCacheItemPolicy;
                cacheEntryRemovedCallback = CacheItemRemoved;
            }
            else
            {
                cacheItemPolicy = _defaultCacheItemPolicy;
            }

            if (absoluteExpiration.HasValue)
            {
                cacheItemPolicy = new CacheItemPolicy {
                    AbsoluteExpiration = absoluteExpiration.Value, RemovedCallback = cacheEntryRemovedCallback
                };
            }
            else if (slidingExpiration.HasValue)
            {
                cacheItemPolicy = new CacheItemPolicy {
                    SlidingExpiration = slidingExpiration.Value, RemovedCallback = cacheEntryRemovedCallback
                };
            }

            // Iterate all cache keys and associated serialized objects
            foreach (var cacheKeysAndSerializedObjectKvp in cacheKeysAndSerializedObjects)
            {
                // Place object in cache
                if (isInterned)
                {
                    _memCache.AddInterned(cacheKeysAndSerializedObjectKvp.Key, cacheKeysAndSerializedObjectKvp.Value);
                }
                else
                {
                    _memCache.Add(cacheKeysAndSerializedObjectKvp.Key, cacheKeysAndSerializedObjectKvp.Value, cacheItemPolicy);
                }

                // Check if adding tag
                if (string.IsNullOrWhiteSpace(tagName))
                {
                    continue;
                }

                // Add to the local tag routing table
                _tagRoutingTable.AddOrUpdate(cacheKeysAndSerializedObjectKvp.Key, tagName);
            }
        }
Пример #11
0
        /// <summary>
        /// 向缓存中设置缓存项
        /// </summary>
        /// <param name="key">该缓存项的唯一标识符。</param>
        /// <param name="value">要插入的对象。</param>
        /// <param name="minutesValue">分钟数,精确到最接近的毫秒。一个时段,必须在此时段内访问某个缓存项,否则将从内存中逐出该缓存项。</param>
        /// <param name="removedCallback">在从缓存中移除某个缓存项后将调用该方法。</param>
        public static void Set(string key, object value, double minutesValue, CacheEntryRemovedCallback RemovedCallback)
        {
            CacheItem       item   = new CacheItem(key, value);
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.SlidingExpiration = TimeSpan.FromMinutes(minutesValue);
            policy.RemovedCallback   = RemovedCallback;
            cache.Set(item, policy);
        }
Пример #12
0
        private static void CreateMemoryCacheItem(double hours = 24.0)
        {
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTime.Now.AddHours(hours);
            CacheEntryRemovedCallback removeCallback = new CacheEntryRemovedCallback(HousekeepingCallback);

            policy.RemovedCallback = removeCallback;
            _ = MemoryCache.Default.Add(Program.TLMemCacheKey.Housekeeping.ToString(), policy, policy);
        }
Пример #13
0
        /// <inheritdoc />
        public override void Initialize(string name, NameValueCollection config)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = "InProc async session state provider";
            }
            base.Initialize(name, config);

            _callback = new CacheEntryRemovedCallback(OnCacheItemRemoved);
        }
Пример #14
0
        public void AddData(ICacheItem key, object value, int expirationMinutes, CacheEntryRemovedCallback objectExpiredEvent)
        {
            CacheItemPolicy policy = new CacheItemPolicy();

            if (expirationMinutes > 0)
            {
                policy.AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(expirationMinutes);
                policy.RemovedCallback    = objectExpiredEvent;
            }
            MemoryCache.Default.Add(key.ToString(), value, policy);
        }
Пример #15
0
        private static void CacheUsers(string key, object users)
        {
            CacheEntryRemovedCallback usersItemRemovedCallback = UsersItemRemovedCallback;
            var policy = new CacheItemPolicy
            {
                AbsoluteExpiration = DateTime.Now.AddMinutes(60),
                RemovedCallback    = usersItemRemovedCallback
            };

            Cache.Set(key, users, policy);
        }
Пример #16
0
        private static void CacheAccounts(string key, object accounts)
        {
            CacheEntryRemovedCallback accountItemRemovedCallback = AccountItemRemovedCallback;
            var policy = new CacheItemPolicy
            {
                AbsoluteExpiration = DateTime.Now.AddMinutes(60),
                RemovedCallback    = accountItemRemovedCallback
            };

            Cache.Set(key, accounts, policy);
        }
 static LRUSingletonMemoryCache()
 {
     Instance                = new LRUSingletonMemoryCache();
     _memoryCache            = new MemoryCache("LRUSingletonMemoryCache");
     _locks                  = new ConcurrentDictionary <object, SemaphoreSlim>();
     _policy                 = new CacheItemPolicy();
     _lRUQueue               = new LRUQueue();
     removeCallback          = new CacheEntryRemovedCallback(OnRemoved);
     _policy.RemovedCallback = removeCallback;
     _capacity               = 4;
 }
Пример #18
0
        public void AddToMyCache(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, List<String> FilePath)
        {
            callback = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
            policy = new CacheItemPolicy();
            policy.Priority = (MyCacheItemPriority == MyCachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(86400.00);
            policy.RemovedCallback = callback;
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

            // Add inside cache 
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #19
0
        public void AddToMyCache(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, List <String> FilePath)
        {
            callback                  = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
            policy                    = new CacheItemPolicy();
            policy.Priority           = (MyCacheItemPriority == MyCachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(86400.00);
            policy.RemovedCallback    = callback;
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #20
0
 public static void AddToMyCache(string cacheKeyName, PropertyInfo[] cacheItem,
                                 CacheItemPriority cacheItemPriority)
 {
     _callback = MyCachedItemRemovedCallback;
     _policy   = new CacheItemPolicy
     {
         Priority           = cacheItemPriority,
         AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1000.00),
         RemovedCallback    = _callback
     };
     cache.Set(cacheKeyName, cacheItem, _policy);
 }
Пример #21
0
        public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
        {
            if (regionName != null)
            {
                throw new NotSupportedException(SR.RegionName_not_supported);
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            DateTimeOffset             absExp          = ObjectCache.InfiniteAbsoluteExpiration;
            TimeSpan                   slidingExp      = ObjectCache.NoSlidingExpiration;
            CacheItemPriority          priority        = CacheItemPriority.Default;
            Collection <ChangeMonitor> changeMonitors  = null;
            CacheEntryRemovedCallback  removedCallback = null;

            if (policy != null)
            {
                ValidatePolicy(policy);
                if (policy.UpdateCallback != null)
                {
                    Set(key, value, policy.ChangeMonitors, policy.AbsoluteExpiration, policy.SlidingExpiration, policy.UpdateCallback);
                    return;
                }
                absExp          = policy.AbsoluteExpiration;
                slidingExp      = policy.SlidingExpiration;
                priority        = policy.Priority;
                changeMonitors  = policy.ChangeMonitors;
                removedCallback = policy.RemovedCallback;
            }
            if (IsDisposed)
            {
                if (changeMonitors != null)
                {
                    foreach (ChangeMonitor monitor in changeMonitors)
                    {
                        if (monitor != null)
                        {
                            monitor.Dispose();
                        }
                    }
                }

                IsDisposedOrThrow();

                return;
            }
            MemoryCacheKey   cacheKey = new MemoryCacheKey(key);
            MemoryCacheStore store    = GetStore(cacheKey);

            store.Set(cacheKey, new MemoryCacheEntry(key, value, absExp, slidingExp, priority, changeMonitors, removedCallback, this));
        }
Пример #22
0
        internal MemoryCacheEntry(string key,
                                  object value,
                                  DateTimeOffset absExp,
                                  TimeSpan slidingExp,
                                  CacheItemPriority priority,
                                  Collection <ChangeMonitor> dependencies,
                                  CacheEntryRemovedCallback removedCallback,
                                  MemoryCache cache) : base(key)
        {
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            _utcCreated = DateTime.UtcNow;
            _value      = value;

            _slidingExp = slidingExp;
            if (_slidingExp > TimeSpan.Zero)
            {
                _utcAbsExp = _utcCreated + _slidingExp;
            }
            else
            {
                _utcAbsExp = absExp.UtcDateTime;
            }

            _expiresEntryRef = ExpiresEntryRef.INVALID;
            _expiresBucket   = 0xff;

            _usageEntryRef = UsageEntryRef.INVALID;
            if (priority == CacheItemPriority.NotRemovable)
            {
                _usageBucket = 0xff;
            }
            else
            {
                _usageBucket = 0;
            }

            _callback = removedCallback;

            // CacheItemPolicy.ChangeMonitors is frequently the source for 'dependencies', and that property
            // is never null. So check that the collection of dependencies is not empty before allocating
            // the 'seldom' used fields.
            if (dependencies != null && dependencies.Count > 0)
            {
                _fields = new SeldomUsedFields();
                _fields._dependencies = dependencies;
                _fields._cache        = cache;
            }
        }
Пример #23
0
        public void AddToMyCache(String CacheKeyName, Object CacheItem,
                                 MyCachePriority MyCacheItemPriority)
        {
            callback        = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
            policy          = new CacheItemPolicy();
            policy.Priority = (MyCacheItemPriority == MyCachePriority.Default) ?
                              CacheItemPriority.Default : CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddDays(Convert.ToDouble(7));
            policy.RemovedCallback    = callback;

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #24
0
        public void AddToMyCache(String CacheKeyName, Object CacheItem, CachePriority CacheItemPriority, double CacheExpirationSeconds)
        {
            callbackWrapper = new CacheEntryRemovedCallback(this.CacheWrapperCallback);
            policy          = new CacheItemPolicy
            {
                Priority           = (System.Runtime.Caching.CacheItemPriority)CacheItemPriority,
                AbsoluteExpiration = DateTime.Now.AddSeconds(CacheExpirationSeconds),
                RemovedCallback    = callbackWrapper
            };
            //policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #25
0
        /// <summary>
        /// 设置一个在 <paramref name="minutes"/> 分钟后失效的缓存,在失效后调用 <paramref name="callback"/> 进行通知。
        /// </summary>
        public static void SetAbsolute(string key, object data, double minutes, CacheEntryRemovedCallback callback, string domain = null)
        {
            if (data == null)
            {
                throw new ArgumentNullException($"参数 {nameof(data)} 不能为空。");
            }

            var policy = new CacheItemPolicy {
                AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes), RemovedCallback = callback
            };

            Set(key, data, policy, domain);
        }
Пример #26
0
        public void AddToDataCache(String cacheKeyName, Object cacheItem, CachePriority cacheItemPriority, List <String> filePath)
        {
            removalCallback = new CacheEntryRemovedCallback(this.CacheItemRemovedCallback);
            policy          = new CacheItemPolicy();
            policy.Priority = (cacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;

            //policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.00);
            policy.RemovedCallback = removalCallback;
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePath));

            // Add the Item cache
            cache.Set(cacheKeyName, cacheItem, policy);
        }
Пример #27
0
 /// <summary>
 /// AddToCache
 /// T타입을 사용하기 위해서, 메소드 오버라이딩 추가함
 /// 2013.10.15 박정환
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="CacheKeyName"></param>
 /// <param name="value"></param>
 /// <param name="dtOffsetMinutes"></param>
 /// <param name="MyCacheItemPriority"></param>
 public void AddToCache <T>(string CacheKeyName, T value, double dtOffsetMinutes, CachePriority MyCacheItemPriority)
 {
     //Type type = typeof(T);
     callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);
     policy   = new CacheItemPolicy
     {
         Priority           = (MyCacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable,
         AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(dtOffsetMinutes),
         RemovedCallback    = callback
     };
     // Add inside cache
     cache.Set(CacheKeyName, value, policy);
 }
Пример #28
0
        public void Add(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, int Seconds)
        {
            // 
            callback = RemovedCallback;
            policy = new CacheItemPolicy();
            policy.Priority = (MyCacheItemPriority == MyCachePriority.Default)
                ? CacheItemPriority.Default
                : CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(Seconds);
            policy.RemovedCallback = callback;

            // Add inside cache 
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #29
0
        /// <summary>
        /// Add to my cache.
        /// </summary>
        /// <param name="cacheKeyName">
        /// The cache key name.
        /// </param>
        /// <param name="cacheItem">
        /// The cache item.
        /// </param>
        /// <param name="myCacheItemPriority">
        /// The my cache item priority.
        /// </param>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        public void AddToMyCache(string cacheKeyName, object cacheItem, MyCachePriority myCacheItemPriority, List <string> filePath)
        {
            this.callback        = new CacheEntryRemovedCallback(this.MyCachedItemRemovedCallback);
            this.policy          = new CacheItemPolicy();
            this.policy.Priority = (myCacheItemPriority == MyCachePriority.Default)
                                  ? CacheItemPriority.Default
                                  : CacheItemPriority.NotRemovable;
            this.policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(02.00);                               //.AddHours(01.00);     //.AddSeconds(59.00);
            this.policy.RemovedCallback    = this.callback;
            //this.policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePath));

            // Add inside cache
            this.cache.Set(cacheKeyName, cacheItem, this.policy);
        }
Пример #30
0
        public void Add(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, int Seconds)
        {
            //
            callback        = RemovedCallback;
            policy          = new CacheItemPolicy();
            policy.Priority = (MyCacheItemPriority == MyCachePriority.Default)
                ? CacheItemPriority.Default
                : CacheItemPriority.NotRemovable;
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(Seconds);
            policy.RemovedCallback    = callback;

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #31
0
        /// <summary>
        /// 기본캐쉬등록
        /// </summary>
        /// <param name="CacheKeyName"></param>
        /// <param name="CacheItem"></param>
        /// <param name="MyCacheItemPriority"></param>
        public void AddToCache(string CacheKeyName, object CacheItem, CachePriority MyCacheItemPriority)
        {
            //
            callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);
            policy   = new CacheItemPolicy
            {
                Priority           = (MyCacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable,
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60.00),
                RemovedCallback    = callback
            };

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
Пример #32
0
        public void SetPolicy(CacheItemPolicy policy)
        {
            if (policy == null)
            {
                return;
            }

            absoluteExpiration = policy.AbsoluteExpiration;
            monitors           = policy.ChangeMonitors;
            priority           = policy.Priority;
            removedCallback    = policy.RemovedCallback;
            slidingExpiration  = policy.SlidingExpiration;
            updateCallback     = policy.UpdateCallback;
        }
        public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
        {
            if (regionName != null)
            {
                throw new NotSupportedException(R.RegionName_not_supported);
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            DateTimeOffset             infiniteAbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
            TimeSpan                   noSlidingExpiration        = ObjectCache.NoSlidingExpiration;
            CacheItemPriority          priority        = CacheItemPriority.Default;
            Collection <ChangeMonitor> dependencies    = null;
            CacheEntryRemovedCallback  removedCallback = null;

            if (policy != null)
            {
                this.ValidatePolicy(policy);
                if (policy.UpdateCallback != null)
                {
                    this.Set(key, value, policy.ChangeMonitors, policy.AbsoluteExpiration, policy.SlidingExpiration, policy.UpdateCallback);
                    return;
                }
                infiniteAbsoluteExpiration = policy.AbsoluteExpiration;
                noSlidingExpiration        = policy.SlidingExpiration;
                priority        = policy.Priority;
                dependencies    = policy.ChangeMonitors;
                removedCallback = policy.RemovedCallback;
            }
            if (this.IsDisposed)
            {
                if (dependencies != null)
                {
                    foreach (ChangeMonitor monitor in dependencies)
                    {
                        if (monitor != null)
                        {
                            monitor.Dispose();
                        }
                    }
                }
            }
            else
            {
                MemoryCacheKey key2 = new MemoryCacheKey(key);
                this.GetStore(key2).Set(key2, new MemoryCacheEntry(key, value, infiniteAbsoluteExpiration, noSlidingExpiration, priority, dependencies, removedCallback, this));
            }
        }
 internal MemoryCacheEntry(string key, object value, DateTimeOffset absExp, TimeSpan slidingExp, CacheItemPriority priority, Collection<ChangeMonitor> dependencies, CacheEntryRemovedCallback removedCallback, MemoryCache cache) : base(key)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     this._utcCreated = DateTime.UtcNow;
     this._value = value;
     this._slidingExp = slidingExp;
     if (this._slidingExp > TimeSpan.Zero)
     {
         this._utcAbsExp = this._utcCreated + this._slidingExp;
     }
     else
     {
         this._utcAbsExp = absExp.UtcDateTime;
     }
     this._expiresEntryRef = System.Runtime.Caching.ExpiresEntryRef.INVALID;
     this._expiresBucket = 0xff;
     this._usageEntryRef = System.Runtime.Caching.UsageEntryRef.INVALID;
     if (priority == CacheItemPriority.NotRemovable)
     {
         this._usageBucket = 0xff;
     }
     else
     {
         this._usageBucket = 0;
     }
     this._callback = removedCallback;
     if (dependencies != null)
     {
         this._fields = new SeldomUsedFields();
         this._fields._dependencies = dependencies;
         this._fields._cache = cache;
     }
 }
Пример #35
0
		public void SetPolicy (CacheItemPolicy policy)
		{
			if (policy == null)
				return;
			
			absoluteExpiration = policy.AbsoluteExpiration;
			monitors = policy.ChangeMonitors;
			priority = policy.Priority;
			removedCallback = policy.RemovedCallback;
			slidingExpiration = policy.SlidingExpiration;
			updateCallback = policy.UpdateCallback;
		}
Пример #36
0
		public MemoryCacheEntry (MemoryCache owner, string key, object value, DateTimeOffset absoluteExpiration, Collection <ChangeMonitor> monitors,
					 CacheItemPriority priority, CacheEntryRemovedCallback removedCallback, TimeSpan slidingExpiration,
					 CacheEntryUpdateCallback updateCallback)
		{
			if (value == null)
				throw new ArgumentNullException ("value");

			if (owner == null)
				throw new ArgumentNullException ("owner");

			this.owner = owner;
			this.Key = key;
			this.Value = value;
			this.absoluteExpiration = absoluteExpiration;
			this.monitors = monitors;
			this.priority = priority;
			this.removedCallback = removedCallback;
			this.slidingExpiration = slidingExpiration;
			this.updateCallback = updateCallback;
			this.LastModified = DateTime.UtcNow;

			if (absoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration)
				expiresAt = absoluteExpiration.Ticks;
			else if (slidingExpiration != ObjectCache.NoSlidingExpiration)
				expiresAt = DateTime.Now.Ticks + slidingExpiration.Ticks;
			else
				expiresAt = 0;
		}
Пример #37
0
        private void StoreRootCacheKey()
        {
            rootCacheKeyStored = true;

            var removedCallback = new CacheEntryRemovedCallback(this.RootCacheItemRemoved);

            //cache.Add(
            //    rootCacheKey,
            //    rootCacheKey,
            //    null,
            //    System.Web.Caching.Cache.NoAbsoluteExpiration,
            //    System.Web.Caching.Cache.NoSlidingExpiration,
            //    CacheItemPriority.Default,
            //    RootCacheItemRemoved);

            CacheItemPolicy cachePolicy = new CacheItemPolicy();

            cachePolicy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
            cachePolicy.SlidingExpiration = ObjectCache.NoSlidingExpiration;
            cachePolicy.Priority = CacheItemPriority.Default;
            cachePolicy.RemovedCallback = removedCallback;

            cache.Add(
                rootCacheKey,
                rootCacheKey,
                cachePolicy);
        }
Пример #38
0
 static CacheItemPolicy GenerateCacheItemPolicy(DateTimeOffset absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheEntryRemovedCallback onRemoveCallback = null)
 {
     var policy = new CacheItemPolicy();
     policy.AbsoluteExpiration = absoluteExpiration;
     policy.SlidingExpiration = slidingExpiration;
     policy.Priority = priority;
     policy.RemovedCallback = onRemoveCallback;
     return policy;
 }