关于WinForm/Web如何使用缓存Cach

Cache 的绝对到期与滑动到期
绝对到期:设置绝对过期时间 到了指定时间以后会失效。(类似Cookie机制)
相对到期也称滑动到期:设置相对过期时间 指定时间内无访问会失效。(类似Session机制)
 

HttpRuntime.Cache与HttpContext.Current.Cache 为同一个对象
HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象 HttpRuntime.Cache.Insert存在相同的键会替换无返回值

HttpRuntime.Cache["key"] 使用字典的方式也可以读取和设置
HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds), TimeSpan.Zero); //设置绝对过期时间 到了指定时间以后会失效 ps: TimeSpan.Zero == System.Web.Caching.Cache.NoSlidingExpiration
HttpRuntime.Cache.Insert(key, value, null, DateTime.MaxValue, TimeSpan.FromSeconds(seconds)); //设置相对过期时间 指定时间内无访问会失效 ps: DateTime.MaxValue == System.Web.Caching.Cache.NoAbsoluteExpiration

本文参考:http://blog.csdn.net/ttotcs/article/details/7476234

System.Web.HttpRuntime.Cache的方法:

Add

Insert

Get

Remove

 

缓存的操作包括:读、写。
读取缓存内容调用System.Web.HttpRuntime.Cache.Get(Key)方法,插入缓存数据调用Add或Insert方法。

 

Add与Insert的不同

HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象。

HttpRuntime.Cache.Insert存在相同的键会替换原值,无返回值。

如果您希望某个缓存项目一旦放入缓存后,就不要再被修改,那么调用Add确实可以防止后来的修改操作。而调用Insert方法,则永远会覆盖已存在项。

 

缓存的过期时间

缓存过期时间包括:绝对过期和滑动过期。

绝对过期:到了指定时间以后便会失效。

滑动过期:在指定时间内无访问请求便失效。

实例:

绝对过期:

HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds),System.Web.Caching.Cache.NoSlidingExpiration);

滑动过期:

HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration
, TimeSpan.FromSeconds(seconds));

缓存项移除优先级

// 指定 Cache 对象中存储的项的相对优先级。
public enum CacheItemPriority
{
    //  在服务器释放系统内存时,具有该优先级级别的缓存项最有可能被从缓存删除。
    Low = 1,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项比分配了 CacheItemPriority.Normal
    //  优先级的项更有可能被从缓存删除。
    BelowNormal = 2,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项很有可能被从缓存删除,
    //  其被删除的可能性仅次于具有 CacheItemPriority.Low
    //  或 CacheItemPriority.BelowNormal 优先级的那些项。这是默认选项。
    Normal = 3,

    //  缓存项优先级的默认值为 CacheItemPriority.Normal。
    Default = 3,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项被删除的可能性
    //  比分配了 CacheItemPriority.Normal 优先级的项要小。
    AboveNormal = 4,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项最不可能被从缓存删除。
    High = 5,

    //  在服务器释放系统内存时,具有该优先级级别的缓存项将不会被自动从缓存删除。
    //  但是,具有该优先级级别的项会根据项的绝对到期时间或可调整到期时间与其他项一起被移除。
    NotRemovable = 6,
}
 

  


 参考文章   http://kb.cnblogs.com/page/69483/

              http://www.cnblogs.com/zgx/archive/2009/03/16/1413643.html

              http://www.cnblogs.com/zhangxp1129/archive/2012/09/05/2671522.html

MSDN:   http://msdn.microsoft.com/zh-cn/magazine/system.web.caching.cache(VS.85).aspx

对于每个应用程序域均创建该类的一个实例,并且只要对应的应用程序域保持活动,该实例便保持有效。

说明注意:

Cache 类不能在 ASP.NET 应用程序外使用。它是为在 ASP.NET 中用于为 Web 应用程序提供缓存而设计和测试的。在其他类型的应用程序(如控制台应用程序或 Windows 窗体应用程序)中,ASP.NET 缓存可能无法正常工作。

System.Web.Caching是用来管理缓存的命名空间,其父级空间是System.Web,由此可见,缓存通常用于Web网站的开发,包括在B/S项目中的开发。

缓存的设计主要是考虑到网络带宽可能会延缓数据的提交与回发,如果把数据保存在客户端,用户就可以直接从客户端读取数据,减少客户端与服务器端的数据交互,提高程序的性能。

那么System.Web.Caching可以使用到WinForm程序中吗?

如果用的是winform,基本上不用想这个问题,因为你的程序本身就在内存里运行着。winfrom 直接用内存用 数据字典如果是

web,缓存就是将常用的数据放到服务器的内存中,当有不同的客户请求相同的数据时,直接从内存读取,以此提高性能。

简单点:WebForm是“瘦客户端”,占用服务器资源。WinForm是“胖客户单”,占用的是本地客户端内存。

推荐两种写法:

一、是web项目中如何使用。

本文转载:http://www.cnblogs.com/wgx0428/p/3181307.html

/// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey">键</param>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
        }
        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }
        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        public static void RemoveAllCache(string CacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(CacheKey);
        }
        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }


  

  

 二、是winform程序中

 (1)静态变量缓存:

View Code
namespace HZ
{
    using System.Collections.Generic;

    /// <summary>
    
/// 全局统一的缓存类
    
/// </summary>
    public class Cache
    {
        private SortedDictionary<stringstring> dic = new SortedDictionary<stringstring>();
        private static volatile Cache instance = null;
        private static object lockHelper = new object();

        private Cache()
        {

        }
        public void Add(string key, string value)
        {
            dic.Add(key, value);
        }
        public void Remove(string key)
        {
            dic.Remove(key);
        }

        public string this[string index]
        {
            get
            {
                if (dic.ContainsKey(index))
                    return dic[index];
                else
                    return null;
            }
            set { dic[index] = value; }
        }

        public static Cache Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockHelper)
                    {
                        if (instance == null)
                        {
                            instance = new Cache();
                        }
                    }
                }
                return instance;
            }
        }
    }
}

 (2)内存缓存MemoryCach:表示实现内存中的缓存的类型。(注意此类仅仅NET4.0以上支持

本文转载:http://www.cnblogs.com/jinzhao/archive/2012/06/11/2545450.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
 
namespace CNBlogs.Zzk.Domain.Entities
{
    public class DictionaryCacheManager<TK, TV>  
    {
        private ObjectCache memoryCache;
 
        public DictionaryCacheManager():this(null){}
        public DictionaryCacheManager(string name)
        {
 
            memoryCache = new MemoryCache(string.Format("{0}-{1}-{2}", typeof (TK).Name, typeof (TV).Name, name));
        }
 
        public TV Get(TK key,Func<TV> getValue)
        {
            if(memoryCache.Contains(key.ToString()))
            {
                return (TV)memoryCache[key.ToString()];
            }
            else
            {
                var policy = new CacheItemPolicy();
                var  v = getValue();
                object o = v;
                memoryCache.Set(key.ToString(), o, policy);
                return v;
            }
        }
 
        public TV Get(TK key, Func<TV> getValue,DateTimeOffset dateTimeOffset)
        {
            if (memoryCache.Contains(key.ToString()))
            {
                return (TV)memoryCache[key.ToString()];
            }
            else
            {
                var v = getValue();
                object o = v;
                memoryCache.Set(key.ToString(), o, dateTimeOffset);
                return v;
            }
        }
 
        public void Clear()
        {
            memoryCache.ToList().ForEach(kv => memoryCache.Remove(kv.Key));
        }
        public void Clear(TK key)
        {
            memoryCache.Remove(key.ToString());
        }
 
    }
}

  

原文地址:https://www.cnblogs.com/51net/p/2986403.html