예제 #1
0
 private void AddTask(string name, int seconds)
 {
     _onCacheRemove = CacheItemRemoved;
     HttpRuntime.Cache.Insert(name, seconds, null,
         DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
         CacheItemPriority.NotRemovable, _onCacheRemove);
 }
 internal override void CacheBuildResult(string cacheKey, BuildResult result, long hashCode, DateTime utcStart)
 {
     if (!BuildResultCompiledType.UsesDelayLoadType(result))
     {
         ICollection virtualPathDependencies = result.VirtualPathDependencies;
         CacheDependency dependencies = null;
         if (virtualPathDependencies != null)
         {
             dependencies = result.VirtualPath.GetCacheDependency(virtualPathDependencies, utcStart);
             if (dependencies != null)
             {
                 result.UsesCacheDependency = true;
             }
         }
         if (result.CacheToMemory)
         {
             CacheItemPriority normal;
             BuildResultCompiledAssemblyBase base2 = result as BuildResultCompiledAssemblyBase;
             if (((base2 != null) && (base2.ResultAssembly != null)) && !base2.UsesExistingAssembly)
             {
                 string assemblyCacheKey = BuildResultCache.GetAssemblyCacheKey(base2.ResultAssembly);
                 Assembly assembly = (Assembly) this._cache.Get(assemblyCacheKey);
                 if (assembly == null)
                 {
                     this._cache.UtcInsert(assemblyCacheKey, base2.ResultAssembly, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
                 }
                 CacheDependency dependency2 = new CacheDependency(0, null, new string[] { assemblyCacheKey });
                 if (dependencies != null)
                 {
                     AggregateCacheDependency dependency3 = new AggregateCacheDependency();
                     dependency3.Add(new CacheDependency[] { dependencies, dependency2 });
                     dependencies = dependency3;
                 }
                 else
                 {
                     dependencies = dependency2;
                 }
             }
             string memoryCacheKey = GetMemoryCacheKey(cacheKey);
             if (result.IsUnloadable)
             {
                 normal = CacheItemPriority.Normal;
             }
             else
             {
                 normal = CacheItemPriority.NotRemovable;
             }
             CacheItemRemovedCallback onRemoveCallback = null;
             if (result.ShutdownAppDomainOnChange || (result is BuildResultCompiledAssemblyBase))
             {
                 if (this._onRemoveCallback == null)
                 {
                     this._onRemoveCallback = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
                 }
                 onRemoveCallback = this._onRemoveCallback;
             }
             this._cache.UtcInsert(memoryCacheKey, result, dependencies, result.MemoryCacheExpiration, result.MemoryCacheSlidingExpiration, normal, onRemoveCallback);
         }
     }
 }
예제 #3
0
파일: CacheHelper.cs 프로젝트: pyfxl/fxlweb
 /// <summary>
 /// 建立缓存,并在移除时执行事件
 /// </summary>
 public static object AddCache(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemovedCallback)
 {
     if (HttpRuntime.Cache[key] == null && value != null)
         return HttpRuntime.Cache.Add(key, value, null, absoluteExpiration, slidingExpiration, priority, onRemovedCallback);
     else
         return null;
 }
		private void AddTask(string name, int seconds)
		{
			_onCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
			HttpRuntime.Cache.Insert(name, seconds, null,
				DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration,
				CacheItemPriority.NotRemovable, _onCacheRemove);
		}
 public void Insert(string key, object value, CacheDependency dependencies,
     DateTime absoluteExpiration, TimeSpan slidingExpiration,
     CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     _cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration,
         priority, onRemoveCallback);
 }
예제 #6
0
		internal CacheEntry (Cache objManager, string strKey, object objItem,CacheDependency objDependency,
				CacheItemRemovedCallback eventRemove, DateTime dtExpires, TimeSpan tsSpan,
				long longMinHits, bool boolPublic, CacheItemPriority enumPriority )
		{
			if (boolPublic)
				_enumFlags |= Flags.Public;

			_strKey = strKey;
			_objItem = objItem;
			_objCache = objManager;
			_onRemoved += eventRemove;
			_enumPriority = enumPriority;
			_ticksExpires = dtExpires.ToUniversalTime ().Ticks;
			_ticksSlidingExpiration = tsSpan.Ticks;

			// If we have a sliding expiration it overrides the absolute expiration (MS behavior)
			// This is because sliding expiration causes the absolute expiration to be 
			// moved after each period, and the absolute expiration is the value used 
			// for all expiration calculations.
			if (tsSpan.Ticks != Cache.NoSlidingExpiration.Ticks)
				_ticksExpires = DateTime.UtcNow.AddTicks (_ticksSlidingExpiration).Ticks;
			
			_objDependency = objDependency;
			if (_objDependency != null)
				// Add the entry to the cache dependency handler (we support multiple entries per handler)
				_objDependency.Changed += new CacheDependencyChangedHandler (OnChanged); 

			_longMinHits = longMinHits;
		}
예제 #7
0
        /// <summary>
        /// 添加缓存 (绝对有效期)
        /// </summary>
        /// <param name="cacheKey">缓存键值</param>
        /// <param name="cacheValue">缓存内容</param>
        /// <param name="timeout">绝对有效期(单位: 秒)</param>
        public static void Set(string cacheKey, object cacheValue, int timeout)
        {

            if (string.IsNullOrEmpty(cacheKey))
            {
                return;
            }

            if (null == cacheValue)
            {
                Remove(cacheKey);
                return;
            }

            CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);

            if (timeout <= 0)
            {
                cache.Insert(cacheKey, cacheValue, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.High, callBack);
            }
            else
            {
                cache.Insert(cacheKey, cacheValue, null, DateTime.Now.AddSeconds(timeout), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, callBack);
            }
        }
예제 #8
0
파일: Caching.cs 프로젝트: NigelYu/NewsSite
 /// <summary>
 /// 本地缓存写入,包括分钟,是否绝对过期及缓存过期的回调
 /// </summary>
 /// <param name="name">key</param>
 /// <param name="value">value</param>
 /// <param name="minutes"缓存分钟></param>
 /// <param name="isAbsoluteExpiration">是否绝对过期</param>
 /// <param name="onRemoveCallback">缓存过期回调</param>
 public static void Set(string name, object value, int minutes, bool isAbsoluteExpiration, CacheItemRemovedCallback onRemoveCallback)
 {
     if (isAbsoluteExpiration)
         HttpRuntime.Cache.Insert(name, value, null, DateTime.Now.AddMinutes(minutes), Cache.NoSlidingExpiration, CacheItemPriority.Normal, onRemoveCallback);
     else
         HttpRuntime.Cache.Insert(name, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes), CacheItemPriority.Normal, onRemoveCallback);
 }
        private void BindSignal(string virtualPath, CacheItemRemovedCallback callback)
        {
            string key = _prefix + virtualPath;

            //PERF: Don't add in the cache if already present. Creating a "CacheDependency"
            //      object (below) is actually quite expensive.
            if (HostingEnvironment.Cache.Get(key) != null)
                return;

            var cacheDependency = HostingEnvironment.VirtualPathProvider.GetCacheDependency(
                virtualPath,
                new[] { virtualPath },
                _clock.UtcNow);

            Logger.Debug("Monitoring virtual path \"{0}\"", virtualPath);

            HostingEnvironment.Cache.Add(
                key,
                virtualPath,
                cacheDependency,
                Cache.NoAbsoluteExpiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable,
                callback);
        }
예제 #10
0
        //TODO: Fix this so the timer doesn't keep running during unit tests.
        public void StartTimer(int secondInterval)
        {
            _onCacheRemove = DoWork;

            HttpRuntime.Cache.Insert(GetType().ToString(), secondInterval, null,
                DateTime.Now.AddSeconds(secondInterval), Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable, _onCacheRemove);
        }
예제 #11
0
        /// <summary>
        /// 加入当前对象到缓存中
        /// </summary>
        /// <param name="objId">key for the object</param>
        /// <param name="o">object</param>
        public void AddObject(string objId, object o)
        {
            if (objId == null || objId.Length == 0 || o == null)
                return;

            CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);
            webCacheforfocus.Insert(objId, o, null, DateTime.Now.AddMinutes(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack);
        }
        public override void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority,
                                   CacheItemRemovedCallback onRemoveCallback)
        {
            //onRemoveCallback += ItemRemovedCallback;

            //Call base class method to add obect to cache
            base.Insert(cacheKey, itemToCache, dependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (String.IsNullOrEmpty(name))
                name = "InProc Session State Provider";
            base.Initialize(name, config);

            _callback = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
        }
예제 #14
0
 static void RemoveFileWithDelayInternal(string fileKey, object fileData, int delay, CacheItemRemovedCallback removeAction) {
     string key = RemoveTaskKeyPrefix + fileKey;
     if(HttpRuntime.Cache[key] == null) {
         DateTime absoluteExpiration = DateTime.UtcNow.Add(new TimeSpan(0, delay, 0));
         HttpRuntime.Cache.Insert(key, fileData, null, absoluteExpiration,
             Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, removeAction);
     }
 }
예제 #15
0
        public static IExpressionRegistration CachedLifetime(this IExpressionRegistration registration, TimeSpan slidingExpiration, CacheDependency dependency = null, CacheItemPriority itemPriority = CacheItemPriority.Default, CacheItemRemovedCallback itemRemovedCallback = null)
        {
            if (registration == null)
                throw new ArgumentNullException("registration");

            registration.SetLifetime(new CachedLifetime(slidingExpiration, dependency, itemPriority, itemRemovedCallback));
            return registration;
        }
예제 #16
0
 public static void Add(string key, object o, int time, TimeSpan timespan, CacheItemPriority priority, CacheItemRemovedCallback callback)
 {
     if (o == null)
     {
         return;
     }
     _cache.Insert(key, o, null, DateTime.Now.AddSeconds(time), timespan, priority, callback);
 }
예제 #17
0
        private void AddTask(string taskName, int seconds)
        {
            // http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
            OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);

            HttpRuntime.Cache.Insert(taskName, seconds, null,
                DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable, OnCacheRemove);
        }
예제 #18
0
 public void Insert(string key, object value, CacheItemRemovedCallback cacheItemRemovedCallback, params string[] fileDependencies)
 {
     if (key.HasValue() && value != null)
     {
         HttpRuntime.Cache.Insert(key, value, fileDependencies.Any() ? new CacheDependency(fileDependencies) : null,
             System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,
             CacheItemPriority.Normal, cacheItemRemovedCallback);
     }
 }
		public void Insert(string Key, object Obj, CacheDependency Dependency, double TimeOut, TimeSpan SlidingExpiration, CacheItemPriority Priority, CacheItemRemovedCallback RemovedCallback)
		{
			if ((Obj != null)) {
				Cache Cache = HttpRuntime.Cache;
				if (Cache [Key] == null) {
					Cache.Insert(Key, RuntimeHelpers.GetObjectValue(Obj), Dependency, DateTime.Now.AddSeconds(TimeOut), SlidingExpiration, Priority, RemovedCallback);
				}
			}
		}
예제 #20
0
        /// <summary>
        /// 增加一个缓存对象
        /// </summary>
        /// <param name="strKey">键值名称</param>
        /// <param name="valueObj">被缓存对象</param>
        /// <param name="timeSpan">缓存失效时间,默认为3分钟</param>
        /// <param name="priority">保留优先级(枚举数值),1最不会被清除,6最容易被内存管理清除,0为default
        /// 【1:NotRemovable;2:High;3:AboveNormal;4:Normal;5:BelowNormal;6:Low】</param>
        /// <returns>缓存写入是否成功true 、 false</returns>
        public static bool InsertCache(string strKey, object valueObj, TimeSpan timeSpan, int priority)
        {
            TimeSpan ts;
            if (strKey != null && strKey.Length != 0 && valueObj != null)
            {
                //建立回调委托的一个实例

                //onRemove是委托执行的函数,具体方法看下面的onRemove(...)
                CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);
                #region 失效时间设置
                if (timeSpan == null)
                {
                    ts = new TimeSpan(0, 3, 0);//如果不进行设置则为三分钟
                }
                else
                {
                    ts = timeSpan;
                }
                #endregion
                #region System.Web.Caching.Cache 对象中存储的项的相对优先级

                CacheItemPriority cachePriority;
                switch (priority)
                {
                    case 6:
                        cachePriority = CacheItemPriority.Low;
                        break;
                    case 5:
                        cachePriority = CacheItemPriority.BelowNormal;
                        break;
                    case 4:
                        cachePriority = CacheItemPriority.Normal;
                        break;
                    case 3:
                        cachePriority = CacheItemPriority.AboveNormal;
                        break;
                    case 2:
                        cachePriority = CacheItemPriority.High;
                        break;
                    case 1:
                        cachePriority = CacheItemPriority.NotRemovable;
                        break;
                    default:
                        cachePriority = CacheItemPriority.Default;
                        break;
                }
                #endregion

                HttpRuntime.Cache.Insert(strKey, valueObj, null, DateTime.Now.Add(ts), System.Web.Caching.Cache.NoSlidingExpiration, cachePriority, callBack);
                return true;
            }
            else
            {
                return false;
            }
        }
예제 #21
0
        public static IConfigurableRegistration CachedLifetime(this IConfigurableRegistration registration, CacheDependency dependency = null, CacheItemPriority itemPriority = CacheItemPriority.Default, CacheItemRemovedCallback itemRemovedCallback = null)
        {
            // HttpCachedLifetime / CachedLifetime ?

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

            registration.SetLifetime(new CachedLifetime(dependency, itemPriority, itemRemovedCallback));
            return registration;
        }
		private void Add(String key, Object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, CacheItemRemovedCallback callback)
		{
			if (value == null)
			{
				this.Delete(key);
			}
			else
			{
				HttpRuntime.Cache.Add(key, value, null, absoluteExpiration, slidingExpiration, priority, callback);
			}
		}
        public void AddItemToCache(Object sender, EventArgs e)
        {
            itemRemoved = false;

            onRemove = new CacheItemRemovedCallback(RemovedCallback);

            if (Cache["Key1"] == null)
                Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);

            lblResult.Text = "Value of cache key: " + Cache["Key1"];
        }
예제 #24
0
 		public static void InsertType (Type type, string filename, string key,
				CacheItemRemovedCallback removed_callback)
 		{
 			//string [] cacheKeys = new string [] { cachePrefix + filename };
			//CacheDependency dep = new CacheDependency (null, cacheKeys);
			CacheDependency dep = new CacheDependency (filename);

			HttpRuntime.Cache.Insert (cacheTypePrefix + key, type, dep,
				Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
				CacheItemPriority.Normal, removed_callback);
		}
예제 #25
0
        /// <summary>
        /// 加入当前对象到缓存中
        /// </summary>
        /// <param name="objId">对象的键值</param>
        /// <param name="o">缓存的对象</param>
        public virtual void AddObjectWith(string objId, object o)
        {
            if (objId == null || objId.Length == 0 || o == null)
            {
                return;
            }

            CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);

            webCache.Insert(objId, o, null, System.DateTime.Now.AddSeconds(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack);
        }
예제 #26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="minutes"></param>
        /// <param name="cacheDependency"></param>
        /// <param name="removeCallback"></param>
        public void Insert(string key, object obj, int minutes, CacheDependency cacheDependency, CacheItemRemovedCallback removeCallback)
        {
            if (String.IsNullOrEmpty(key) || key.Equals("")) return;

            if (null == obj) return;

            if (minutes >0)
                _cache.Insert(key, obj, cacheDependency, DateTime.Now.AddSeconds(minutes * 60), TimeSpan.Zero, CacheItemPriority.High, removeCallback);
            else
                _cache.Insert(key, obj, cacheDependency, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.High, removeCallback);
        }
		public void Init (HttpApplication app)
		{
			app.AddOnResolveRequestCacheAsync (
				new BeginEventHandler (OnBeginRequestCache),
				new EndEventHandler (OnEndRequestCache));

			app.AddOnUpdateRequestCacheAsync (
				new BeginEventHandler (OnBeginUpdateCache),
				new EndEventHandler (OnEndUpdateCache));
 
			response_removed = new CacheItemRemovedCallback (OnRawResponseRemoved);
		}
 public override void Insert(string Key, object Value, CommonLibrary.Services.Cache.CacheDependency Dependency, System.DateTime AbsoluteExpiration, System.TimeSpan SlidingExpiration, CacheItemPriority Priority, CacheItemRemovedCallback OnRemoveCallback)
 {
     CommonLibrary.Services.Cache.CacheDependency d = Dependency;
     if (IsWebFarm())
     {
         string[] f = new string[1];
         f[0] = GetFileName(Key);
         CreateCacheFile(f[0], Key);
         d = new CommonLibrary.Services.Cache.CacheDependency(f, null, Dependency);
     }
     base.Insert(Key, Value, d, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback);
 }
예제 #29
0
        /// <summary>
        /// 加入当前对象到缓存中,并使用依赖键
        /// </summary>
        /// <param name="CacheName">对象的键值</param>
        /// <param name="o">缓存的对象</param>
        /// <param name="dependKey">依赖关联的键值</param>
        public void AddObjectWithDepend(string CacheName, object o, string[] DependKey)
        {
            if (CacheName == null || CacheName.Length == 0 || o == null)
            {
                return;
            }

            CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(CacheOnRemove);

            CacheDependency dep = new CacheDependency(null, DependKey, DateTime.Now);

            webcache.Insert(CacheName, o, dep, System.DateTime.Now.AddMinutes(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack);
        }
예제 #30
0
 private void AddTask(string name, int seconds)
 {
     try
     {
         _onCacheRemove = CacheItemRemoved;
         HttpRuntime.Cache.Insert(name, seconds, null,
             DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
             CacheItemPriority.NotRemovable, _onCacheRemove);
     }
     catch (Exception ex)
     {
         logger.Warn("AddTask", ex);
     }
 }
예제 #31
0
 /// <summary>
 /// Inserts the specified cache key.
 /// </summary>
 /// <param name="cacheKey">The cache key.</param>
 /// <param name="itemToCache">The value.</param>
 /// <param name="dependency">The dependency.</param>
 /// <param name="absoluteExpiration">The absolute expiration.</param>
 /// <param name="slidingExpiration">The sliding expiration.</param>
 /// <param name="priority">The priority.</param>
 /// <param name="onRemoveCallback">The on remove callback.</param>
 public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority,
                            CacheItemRemovedCallback onRemoveCallback)
 {
     Cache.Insert(cacheKey, itemToCache, dependency == null ? null : dependency.SystemCacheDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
 }
예제 #32
0
 public virtual void Insert(string cacheKey, object itemToCache, CacheDependency objDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     Insert(cacheKey, itemToCache, new DNNCacheDependency(objDependency), absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
 }
예제 #33
0
        /// <summary>
        /// Adds the specified entry to the cache.
        /// </summary>
        /// <param name="key">The entry key.</param>
        /// <param name="value">The entry value.</param>
        /// <param name="dependentEntitySets">The list of dependent entity sets.</param>
        /// <param name="slidingExpiration">The sliding expiration.</param>
        /// <param name="absoluteExpiration">The absolute expiration.</param>
        /// <param name="callback">callback</param>
        private void PutItemExec(string key, object value, IEnumerable <string> dependentEntitySets, TimeSpan slidingExpiration, DateTime absoluteExpiration, CacheItemRemovedCallback callback)
        {
            key = GetCacheKey(key);
            var cache = HttpCache;

            CacheDependency cd = null;

            if (dependentEntitySets != null)
            {
                var l = dependentEntitySets.ToList();
                foreach (var entitySet in l)
                {
                    EnsureEntryExists(DependentEntitySetPrefix + entitySet);
                }

                if (l.Count > 0)
                {
                    cd = new CacheDependency(new string[0], l.Select(c => DependentEntitySetPrefix + c).ToArray());
                }
            }

            try
            {
                cache.Insert(key, value, cd, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, callback);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    Logger.Error(ex);
                    ex = ex.InnerException;
                }
                // there's a possibility that one of the dependencies has been evicted by another thread
                // in this case just don't put this item in the cache
            }
        }
예제 #34
0
 public T Add <T>(string cacheKey, T value, ICacheItemExpiration expiration, CacheItemRemovedCallback removeCallback = null)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Cache_Add
 /// </summary>
 /// <param name="cacheKey">key</param>
 /// <param name="cacheValue">object value</param>
 /// <param name="keepMinutes"></param>
 /// <param name="dependencies">缓存的依赖项,也就是此项的更改意味着缓存内容已经过期。如果没有依赖项,可将此值设置为NULL。</param>
 /// <param name="cacheItemRemovedCallback">表示缓存删除数据对象时调用的事件,一般用做通知程序。</param>
 /// <returns></returns>
 public static Boolean Cache_Add(string cacheKey, object cacheValue, DateTime expireTime, CacheDependency dependencies = null, CacheItemRemovedCallback cacheItemRemovedCallback = null)
 {
     HttpRuntime.Cache.Insert(cacheKey, cacheValue, dependencies, expireTime, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, cacheItemRemovedCallback);
     return(true);
 }
        public void InsertCacheItem(string cacheKey, Func <object> getCacheItem, TimeSpan?timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null)
        {
            CacheDependency dependency = null;

            if (dependentFiles != null && dependentFiles.Any())
            {
                dependency = new CacheDependency(dependentFiles);
            }
            InsertCacheItem(cacheKey, getCacheItem, timeout, isSliding, priority, removedCallback, dependency);
        }
예제 #37
0
 public static void SetCache(string CacheKey, object objObject, CacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority,
                             CacheItemRemovedCallback OnRemoveCallback)
 {
     SetCache(CacheKey, objObject, new DNNCacheDependency(objDependency), AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback);
 }
        /// <summary>
        /// This overload is here for legacy purposes
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="getCacheItem"></param>
        /// <param name="timeout"></param>
        /// <param name="isSliding"></param>
        /// <param name="priority"></param>
        /// <param name="removedCallback"></param>
        /// <param name="dependency"></param>
        /// <returns></returns>
        internal object GetCacheItem(string cacheKey, Func <object> getCacheItem, TimeSpan?timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null)
        {
            cacheKey = GetCacheKey(cacheKey);

            // NOTE - because we don't know what getCacheItem does, how long it will take and whether it will hang,
            // getCacheItem should run OUTSIDE of the global application lock else we run into lock contention and
            // nasty performance issues.

            // So.... we insert a Lazy<object> in the cache while holding the global application lock, and then rely
            // on the Lazy lock to ensure that getCacheItem runs once and everybody waits on it, while the global
            // application lock has been released.

            // NOTE
            //   The Lazy value creation may produce a null value.
            //   Must make sure (for backward compatibility) that we pretend they are not in the cache.
            //   So if we find an entry in the cache that already has its value created and is null,
            //   pretend it was not there. If value is not already created, wait... and return null, that's
            //   what prior code did.

            // NOTE
            //   The Lazy value creation may throw.

            // So... the null value _will_ be in the cache but never returned

            Lazy <object> result;

            // Fast!
            // Only one thread can enter an UpgradeableReadLock at a time, but it does not prevent other
            // threads to enter a ReadLock in the meantime -- only upgrading to WriteLock will prevent all
            // reads. We first try with a normal ReadLock for maximum concurrency and take the penalty of
            // having to re-lock in case there's no value. Would need to benchmark to figure out whether
            // it's worth it, though...
            try
            {
                _locker.EnterReadLock();
                result = _cache.Get(cacheKey) as Lazy <object>; // null if key not found
            }
            finally
            {
                if (_locker.IsReadLockHeld)
                {
                    _locker.ExitReadLock();
                }
            }
            var value = result == null ? null : GetSafeLazyValue(result);

            if (value != null)
            {
                return(value);
            }

            using (var lck = new UpgradeableReadLock(_locker))
            {
                result = _cache.Get(cacheKey) as Lazy <object>; // null if key not found

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

                if (result == null || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null
                {
                    result = GetSafeLazy(getCacheItem);
                    var absolute = isSliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : (timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value));
                    var sliding  = isSliding == false ? System.Web.Caching.Cache.NoSlidingExpiration : (timeout ?? System.Web.Caching.Cache.NoSlidingExpiration);

                    lck.UpgradeToWriteLock();
                    //NOTE: 'Insert' on System.Web.Caching.Cache actually does an add or update!
                    _cache.Insert(cacheKey, result, dependency, absolute, sliding, priority, removedCallback);
                }
            }

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

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

            value = result.Value; // will not throw (safe lazy)
            if (value is ExceptionHolder eh)
            {
                eh.Exception.Throw();                              // throw once!
            }
            return(value);
        }
        /// <summary>
        /// This overload is here for legacy purposes
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="getCacheItem"></param>
        /// <param name="timeout"></param>
        /// <param name="isSliding"></param>
        /// <param name="priority"></param>
        /// <param name="removedCallback"></param>
        /// <param name="dependency"></param>
        internal void InsertCacheItem(string cacheKey, Func <object> getCacheItem, TimeSpan?timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null)
        {
            // NOTE - here also we must insert a Lazy<object> but we can evaluate it right now
            // and make sure we don't store a null value.

            var result = GetSafeLazy(getCacheItem);
            var value  = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache

            if (value == null)
            {
                return;                // do not store null values (backward compat)
            }
            cacheKey = GetCacheKey(cacheKey);

            var absolute = isSliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : (timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value));
            var sliding  = isSliding == false ? System.Web.Caching.Cache.NoSlidingExpiration : (timeout ?? System.Web.Caching.Cache.NoSlidingExpiration);

            try
            {
                _locker.EnterWriteLock();
                //NOTE: 'Insert' on System.Web.Caching.Cache actually does an add or update!
                _cache.Insert(cacheKey, result, dependency, absolute, sliding, priority, removedCallback);
            }
            finally
            {
                if (_locker.IsWriteLockHeld)
                {
                    _locker.ExitWriteLock();
                }
            }
        }
예제 #40
0
 /// <summary>
 /// 本地缓存写入,包括分钟,是否绝对过期及缓存过期的回调
 /// </summary>
 /// <param name="name">key</param>
 /// <param name="value">value</param>
 /// <param name="minutes"缓存分钟></param>
 /// <param name="isAbsoluteExpiration">是否绝对过期</param>
 /// <param name="onRemoveCallback">缓存过期回调</param>
 public static void Set(string name, object value, int minutes, bool isAbsoluteExpiration, CacheItemRemovedCallback onRemoveCallback)
 {
     if (isAbsoluteExpiration)
     {
         HttpRuntime.Cache.Insert(name, value, null, DateTime.Now.AddMinutes(minutes), Cache.NoSlidingExpiration, CacheItemPriority.Normal, onRemoveCallback);
     }
     else
     {
         HttpRuntime.Cache.Insert(name, value, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes), CacheItemPriority.Normal, onRemoveCallback);
     }
 }
예제 #41
0
 //------------------------提供给上面方法进行调用-----------------------------------
 /// <summary>
 /// 设置缓存
 /// </summary>
 public static bool Set(string key, object value, CacheDependency cacheDependency, DateTime dateTime,
                        TimeSpan timeSpan, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback)
 {
     if (string.IsNullOrEmpty(key) || value == null)
     {
         return(false);
     }
     HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority,
                              cacheItemRemovedCallback);
     return(true);
 }
 public Object Add(string key, Object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     return(default(Object));
 }
예제 #43
0
 /// <summary>
 /// 添加缓存(如果缓存键已经存在,则此方法调用无效)
 /// </summary>
 /// <typeparam name="T">类型</typeparam>
 /// <param name="key">缓存键</param>
 /// <param name="value">值</param>
 /// <param name="callback">回调函数</param>
 /// <param name="CacheTimeOption">缓存时间</param>
 public static void Set <T>(string key, T value, CacheTimeOption CacheTimeOption, CacheItemRemovedCallback callback)
 {
     Set(key, value, CacheTimeOption, CacheExpirationOption.AbsoluteExpiration, null, CacheItemPriority.NotRemovable, callback);
 }
예제 #44
0
        private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback)
        {
            DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime);

            DataCache.SetCache(key,
                               value,
                               dependency,
                               absoluteExpiration,
                               Cache.NoSlidingExpiration,
                               CacheItemPriority.AboveNormal,
                               callback);
        }
예제 #45
0
 // 主调方法
 /// <summary>
 /// 添加缓存(如果缓存键已经存在,则此方法调用无效)
 /// </summary>
 /// <typeparam name="T">类型</typeparam>
 /// <param name="key">缓存键</param>
 /// <param name="value">值</param>
 /// <param name="CacheTimeOption">缓存的时间长短</param>
 /// <param name="CacheExpirationOption"></param>
 /// <param name="dependencies">缓存依赖项</param>
 /// <param name="cacheItemPriority">优先级</param>
 /// <param name="callback">回调函数</param>
 public static void Set <T>(string key, T value, CacheTimeOption CacheTimeOption, CacheExpirationOption CacheExpirationOption,
                            CacheDependency dependencies, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback callback)
 {
     if (!value.Equals(default(T)) && CacheTimeOption != CacheTimeOption.None)
     {
         DateTime absoluteExpiration = GetAbsoluteExpirationTime(CacheTimeOption, CacheExpirationOption);
         TimeSpan slidingExpiration  = GetSlidingExpirationTime(CacheTimeOption, CacheExpirationOption);
         HttpRuntime.Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, cacheItemPriority, callback);
     }
 }
예제 #46
0
 public static void Insert(string key, object value, CacheDependency dependency, CacheItemPriority priority, CacheItemRemovedCallback callback)
 {
     _cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(SaveTime), priority, callback);
 }
 /// <summary>
 /// Cache_Add
 /// </summary>
 /// <param name="cacheKey">key</param>
 /// <param name="cacheValue">object value</param>
 /// <param name="keepMinutes"></param>
 /// <param name="dependencies">缓存的依赖项,也就是此项的更改意味着缓存内容已经过期。如果没有依赖项,可将此值设置为NULL。</param>
 /// <param name="cacheItemRemovedCallback">表示缓存删除数据对象时调用的事件,一般用做通知程序。</param>
 /// <returns></returns>
 public static Boolean Cache_Add(string cacheKey, object cacheValue, int keepMinutes = 10, CacheDependency dependencies = null, CacheItemRemovedCallback cacheItemRemovedCallback = null)
 {
     HttpRuntime.Cache.Insert(cacheKey, cacheValue, dependencies, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(keepMinutes), CacheItemPriority.NotRemovable, cacheItemRemovedCallback);
     return(true);
 }
예제 #48
0
 public static void Insert(string key, object value, CacheDependency dependency, CacheItemRemovedCallback callback)
 {
     Insert(key, value, dependency, CacheItemPriority.Default, callback);
 }
예제 #49
0
 public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     TCache.Insert(key, obj, dep, seconds, priority, onRemoveCallback);
 }
예제 #50
0
 /// <summary>
 /// 建立缓存
 /// </summary>
 public static object TryAddCache(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemovedCallback)
 {
     if (GetCache(key) == null && value != null)
     {
         return(HttpRuntime.Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemovedCallback));
     }
     else
     {
         return(null);
     }
 }
예제 #51
0
 public T Add <T>(string cacheKey, T value, TimeSpan?expire = null, CacheItemRemovedCallback removeCallback = null)
 {
     throw new NotImplementedException();
 }
 /// <inheritdoc />
 public void Insert(string key, Func <object> factory, TimeSpan?timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null)
 {
     InnerCache.Insert(key, () =>
     {
         var result = FastDictionaryAppCacheBase.GetSafeLazy(factory);
         var value  = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache
         // do not store null values (backward compat), clone / reset to go into the cache
         return(value == null ? null : CheckCloneableAndTracksChanges(value));
     }, timeout, isSliding, priority, removedCallback, dependentFiles);
 }
예제 #53
0
        /// <summary>
        /// 建立一个Exist缓存
        /// </summary>
        protected void TryAddExistCache(object existKey, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemovedCallback)
        {
            string key = basicKey + CACHEHEADER_EXISTS + existKey.ToString();

            TryAddCache(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemovedCallback);
        }
예제 #54
0
        public virtual object Add(string CacheKey, object objObject, CacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority, CacheItemRemovedCallback OnRemoveCallback)
        {
            object retValue = GetItem(CacheKey);

            if (retValue == null)
            {
                Insert(CacheKey, objObject, new DNNCacheDependency(objDependency), AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback);
            }
            return(retValue);
        }
예제 #55
0
        /// <summary>
        /// 增加一个缓存对象
        /// </summary>
        /// <param name="strKey">键值名称</param>
        /// <param name="valueObj">被缓存对象</param>
        /// <param name="durationMin">缓存失效时间,默认为3分钟</param>
        /// <param name="priority">保留优先级(枚举数值),1最不会被清除,6最容易被内存管理清除,0为default
        /// 【1:NotRemovable;2:High;3:AboveNormal;4:Normal;5:BelowNormal;6:Low】</param>
        /// <returns>缓存写入是否成功true 、 false</returns>
        public static bool InsertCach(string strKey, object valueObj, int durationMin, int priority)
        {
            TimeSpan ts;

            if (strKey != null && strKey.Length != 0 && valueObj != null)
            {
                //建立回调委托的一个实例

                //onRemove是委托执行的函数,具体方法看下面的onRemove(...)
                var callBack = new CacheItemRemovedCallback(OnRemove);
                #region 失效时间设置
                if (durationMin == 0)
                {
                    ts = new TimeSpan(0, 3, 0);//如果不进行设置则为三分钟
                }
                else
                {
                    ts = new TimeSpan(0, durationMin, 0);
                }
                #endregion
                #region System.Web.Caching.Cache 对象中存储的项的相对优先级

                CacheItemPriority cachePriority;
                switch (priority)
                {
                case 6:
                    cachePriority = CacheItemPriority.Low;
                    break;

                case 5:
                    cachePriority = CacheItemPriority.BelowNormal;
                    break;

                case 4:
                    cachePriority = CacheItemPriority.Normal;
                    break;

                case 3:
                    cachePriority = CacheItemPriority.AboveNormal;
                    break;

                case 2:
                    cachePriority = CacheItemPriority.High;
                    break;

                case 1:
                    cachePriority = CacheItemPriority.NotRemovable;
                    break;

                default:
                    cachePriority = CacheItemPriority.Default;
                    break;
                }
                #endregion
                HttpContext.Current.Cache.Insert(strKey, valueObj, null, DateTime.Now.Add(ts), System.Web.Caching.Cache.NoSlidingExpiration, cachePriority, callBack);
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #56
0
        private CacheItem CreateCacheItem <T>(string cacheKey, Func <T> factory, Func <ICacheItemExpiration> expiration, CacheItemRemovedCallback removeCallback)
        {
            cacheDictionary.CheckCapacity(cacheKey, Capacity, optimizer.CurrentMaxGen, NotifyCacheRemoved);

            return(new CacheItem(
                       cacheKey,
                       factory(),
                       expiration == null ? null : expiration(),
                       removeCallback));
        }
예제 #57
0
        /// <summary>
        /// 将对象插入到缓存管理器中。
        /// </summary>
        /// <typeparam name="T">缓存对象的类型。</typeparam>
        /// <param name="cacheKey">用于引用对象的缓存键。</param>
        /// <param name="value">要插入到缓存的对象。</param>
        /// <param name="expire">对象存放于缓存中的有效时间,到期后将从缓存中移除。如果此值为 null,则默认有效时间为 30 分钟。</param>
        /// <param name="removeCallback">当对象从缓存中移除时,使用该回调方法通知应用程序。</param>
        public T Add <T>(string cacheKey, T value, TimeSpan?expire = null, CacheItemRemovedCallback removeCallback = null)
        {
            cacheDictionary.AddOrUpdate(cacheKey, () => CreateCacheItem(cacheKey, () => value, () => expire == null ? RelativeTime.Default : new RelativeTime(expire.Value), removeCallback));

            return(value);
        }
예제 #58
0
        /// <summary>
        /// 将对象插入到缓存管理器中。
        /// </summary>
        /// <typeparam name="T">缓存对象的类型。</typeparam>
        /// <param name="cacheKey">用于引用对象的缓存键。</param>
        /// <param name="value">要插入到缓存的对象。</param>
        /// <param name="expiration">判断对象过期的对象。</param>
        /// <param name="removeCallback">当对象从缓存中移除时,使用该回调方法通知应用程序。</param>
        public T Add <T>(string cacheKey, T value, ICacheItemExpiration expiration, CacheItemRemovedCallback removeCallback = null)
        {
            cacheDictionary.AddOrUpdate(cacheKey, () => CreateCacheItem(cacheKey, () => value, () => expiration ?? RelativeTime.Default, removeCallback));

            return(value);
        }
예제 #59
0
 private void AddTask(string name, int seconds)
 {
     OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
     HttpRuntime.Cache.Insert(name, seconds, null, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove);
 }
 public void Insert(string key, Object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
 }