asp.net cache.count 报错

 

asp.net cache.count 报错,未将对象引用到对象实例,错误:

对应的Cache实例不是null,但是调用实例方法或者方位实例属性时候还是报错。

原因:

使用cache类自己创建了实例,在Asp.net的iis的进程中出错了

public Cache _cache=new Cache()

 

解决方案:

不自定义实例Catche实例,使用框架自带的实例

  System.We.Caching命名空间中的Cache类是一个用于缓存常用信息的类,HttpRuntime.Cache以及HttpContext.Cache都是该类的实例。

 

一、属性
属性 说明
Count 获取存储在缓存中的项数。
EffectivePercentagePhysicalMemoryLimit 获取在 ASP.NET 开始从缓存中移除项之前应用程序可使用的物理内存百分比。
EffectivePrivateBytesLimit 获取可用于缓存的字节数。
Item 获取或设置指定键处的缓存项。
二、方法
方法名称 说明
Add 将指定项添加到 Cache 对象,该对象具有依赖项、到期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序)。
Get 从 Cache 对象检索指定项。
GetEnumerator 检索用于循环访问包含在缓存中的键设置及其值的字典枚举数。
Insert(String, Object) 向 Cache 对象插入项,该项带有一个缓存键引用其位置,并使用 CacheItemPriority 枚举提供的默认值。
Insert(String, Object, CacheDependency) 向 Cache 中插入具有文件依赖项或键依赖项的对象。
Insert(String, Object, CacheDependency, DateTime, TimeSpan) 向 Cache 中插入具有依赖项和到期策略的对象。
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback) 将对象与依赖项、到期策略以及可用于在从缓存中移除项之前通知应用程序的委托一起插入到 Cache 对象中。
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) 向 Cache 对象中插入对象,后者具有依赖项、到期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序)。
Remove 从应用程序的 Cache 对象移除指定项。
 

三、静态字段
名称 说明
NoAbsoluteExpiration  用于 Insert 方法调用中的 absoluteExpiration 参数中以指示项从不到期。 此字段为只读。
NoSlidingExpiration 用作 Insert 或 Add 方法调用中的 slidingExpiration 参数,以禁用可调到期。 此字段为只读。

四、使用实例:

 

        public Cache _memoryCache = HttpRuntime.Cache;
        /// <summary>
        /// 对应站点ID 
        /// </summary>
        public int SiteID { get; set; }
        /// <summary>
        /// 获取链接地址
        /// </summary>
        /// <returns></returns>
        public string GetLink()
        {
            。。。。。。
        }
        private string GetKey()
        {
            return  "key"+this.SiteID.ToString();
        }
        /// <summary>
        /// 执行加载数据 
        /// </summary>
        /// <returns></returns>
        public string LoadData()
        {
            //判断缓存中是否存在,否则获取更新
            try
            {
                object data = _memoryCache.Get(GetKey());
                if (data!=null)
                {
                    return data.ToString();
                }
                else
                {
                    string html = NetHelper.Get(GetLink());
                    _memoryCache.Insert(GetKey(), html, new CacheDependency(null,new string[] { "key"}), DateTime.MaxValue, new TimeSpan(1, 0, 0));
                    return html;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 清空缓存数据
        /// </summary>
        public void Clear()
        {
            _memoryCache.Remove(GetKey());
        }

 

 

更多:

C# 获取字符串字节长度

.net里Release的pdb文件有什么用 是否可以删除 

.Net AppDomain详解(二) 

posted @ 2020-01-28 11:51  天马3798  阅读(235)  评论(0编辑  收藏  举报