HttpContext.Current.Cache和HttpRuntime.Cache的区别,以及System.Runtime.Caching

先看MSDN上的解释:
      HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。
      HttpRuntime.Cache:获取当前应用程序的Cache。 
      我们再用.NET Reflector工具看看HttpContext.Cache和HttpRuntime.Cache的实现:

HttpContext.Cache和HttpRuntime.Cache实现
    //System.Web.HttpContext.Cache属性实现
    public sealed class HttpContext
    {
        public Cache Cache
        {
            get
            {
                return HttpRuntime.Cache;
            }
        }
    }


    //System.Web.HttpRuntime.Cache属性实现
    public sealed class HttpRuntime
    {
        public static Cache Cache
        {
            get
            {
                if (AspInstallDirectoryInternal == null)
                {
                    throw new HttpException(SR.GetString("Aspnet_not_installed", new object[] { VersionInfo.SystemWebVersion }));
                }
                Cache cache = _theRuntime._cachePublic;
                if (cache == null)
                {
                    CacheInternal cacheInternal = CacheInternal;
                    CacheSection cacheSection = RuntimeConfig.GetAppConfig().Cache;
                    cacheInternal.ReadCacheInternalConfig(cacheSection);
                    _theRuntime._cachePublic = cacheInternal.CachePublic;
                    cache = _theRuntime._cachePublic;
                }
                return cache;
            }
        }
    }

       通过上面的代码我们可以看出:HttpContext.Current.Cache是调用HttpRuntime.Cache实现的,两者指向同一Cache对象。那么两者到底有没有区别的?既然两个指向的是同一Cache对象,两者的差别只能出现在HttpContext和HttpRuntime上了。我们再来看看MSDN中HttpContext和HttpRuntime的定义。
      HttpContext:封装有关个别HTTP请求的所有HTTP特定的信息,HttpContext.Current为当前的HTTP请求获取HttpContext对象。
      HttpRuntime:为当前应用程序提供一组ASP.NET运行时服务。

      由上面的定义可以看出:HttpRuntime.Cache相当于就是一个缓存具体实现类,这个类虽然被放在了System.Web命名空间下,但是非Web应用下也是可以使用;HttpContext.Current.Cache是对上述缓存类的封装,由于封装到了HttpContext类中,局限于只能在知道HttpContext下使用,即只能用于Web应用。

      下面的例子可以很好的说明这一点:

HttpContext.Cache和HttpRuntime.Cache的示例
    class CacheTest
    {
        static void Main(string[] args)
        {       
            System.Web.Caching.Cache httpRuntimeCache = System.Web.HttpRuntime.Cache;
            httpRuntimeCache.Insert("httpRuntimeCache", "I am stored in HttpRuntime.Cache");

            if (httpRuntimeCache != null)
            {
                Console.WriteLine("httpRuntimeCache:" + httpRuntimeCache["httpRuntimeCache"]);
            }

            System.Web.HttpContext httpContext = System.Web.HttpContext.Current;
            if (httpContext == null)
            {
                Console.WriteLine("HttpContext object is null in Console Project");
            }
            else
            {
                System.Web.Caching.Cache httpContextCache = httpContext.Cache;
                httpContextCache.Insert("httpContextCache", "I am stored in HttpRuntime.Cache");
                if (httpContextCache == null)
                {
                    Console.WriteLine("httpContextCache is null");
                }
            }
             
            Console.ReadLine();
        }
    }

      输出结果:httpRuntimeCache:I am stored in HttpRuntime.Cache
      HttpContext object is null in Console Project

      综上:我们在使用Cache时,尽量使用HttpRuntime.Cache,既能减少出错,也减少了一次函数调用。

      参考资料:HttpRuntime.Cache 与HttpContext.Current.Cache的疑问,HttpRuntime.Cache vs. HttpContext.Current.Cache

 

出处:http://blog.csdn.net/qwlovedzm/article/details/7024405

===============================================================================

下面我们看看简单的缓存类处理:

复制代码
using System;
using System.Collections;
using System.Web;
using System.Web.Caching;

namespace aaaaa.Api.Business
{
    /// <summary>
    /// 缓存类
    /// </summary>
    public class CacheHelper
    {
        /// <summary>
        /// 增加一个缓存对象
        /// </summary>
        /// <param name="strKey">键值名称</param>
        /// <param name="valueObj">被缓存对象</param>
        /// <param name="durationMin">缓存失效时间(默认为5分钟)</param>
        /// <param name="cachePriority">保留优先级(枚举数值)</param>
        /// <returns>缓存写入是否成功true 、false</returns>
        public static bool InsertCach(string strKey, object valueObj, int durationMin,
            CacheItemPriority cachePriority = CacheItemPriority.Default)
        {
            TimeSpan ts;
            if (!string.IsNullOrWhiteSpace(strKey) && valueObj != null)
            {
                //onRemove是委托执行的函数,具体方法看下面的onRemove(...)
                CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);
                ts = durationMin == 0 ? new TimeSpan(0, 5, 0) : new TimeSpan(0, durationMin, 0);
                //HttpContext.Current.Cache.Insert(
                HttpRuntime.Cache.Insert(
                    strKey,
                    valueObj,
                    null,
                    DateTime.Now.Add(ts),
                    Cache.NoSlidingExpiration,
                    cachePriority,
                    callBack
                );
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 判断缓存对象是否存在
        /// </summary>
        /// <param name="strKey">缓存键值名称</param>
        /// <returns>是否存在true 、false</returns>
        public static bool IsExist(string strKey)
        {
            //return HttpContext.Current.Cache[strKey] != null;
            return HttpRuntime.Cache.Get(strKey) != null;
        }

        /// <summary>
        /// 读取缓存对象
        /// </summary>
        /// <param name="strKey">缓存键值名称</param>
        /// <returns>缓存对象,objec类型</returns>
        public static object GetCache(string strKey)
        {
            //if (HttpContext.Current.Cache[strKey] != null)
            if (IsExist(strKey))
            {
                object obj = HttpRuntime.Cache.Get(strKey);
                return obj ?? null;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 移除缓存对象
        /// </summary>
        /// <param name="strKey">缓存键值名称</param>
        public static void Remove(string strKey)
        {
            //if (HttpContext.Current.Cache[strKey] != null)
            if (IsExist(strKey))
            {
                HttpRuntime.Cache.Remove(strKey);
            }
        }

        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public static void Clear()
        {
            IDictionaryEnumerator enu = HttpRuntime.Cache.GetEnumerator();
            while (enu.MoveNext())
            {
                Remove(enu.Key.ToString());
            }
        }

        public static CacheItemRemovedReason reason;
        /// <summary>
        /// 此方法在值失效之前调用,可以用于在失效之前更新数据库,或从数据库重新获取数据
        /// </summary>
        /// <param name="strKey"></param>
        /// <param name="obj"></param>
        /// <param name="reason"></param>
        private static void onRemove(string strKey, object obj, CacheItemRemovedReason r)
        {
            reason = r;
        }

        //...

    }
}
复制代码

 

出处:http://blog.csdn.net/joyhen/article/details/40379145

=======================================================================

引用:System.Runtime.Caching.dll,如下测试,fm4.5

复制代码
static void CacheTest()
        {
            string cname = "filescontents";
            ObjectCache cc = MemoryCache.Default;
            string fileContents = cc[cname] as string;

            if (fileContents == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();

                TimeSpan sp = new TimeSpan(0, 1, 0);
                policy.SlidingExpiration = sp;

                List<string> filePaths = new List<string>();
                string path = System.IO.Directory.GetCurrentDirectory() + "\\example.txt";
                filePaths.Add(path);

                policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));

                fileContents = System.IO.File.ReadAllText(path, Encoding.Default);
                cc.Set(cname, fileContents, policy);
            }

            Console.WriteLine(fileContents);
        }


static void Main(string[] args)
        {
            //ExecuteCode(WriteData);
            //ExecuteCode(ReadData);
            //ExecuteCode(TransData);
            bool quit = false;
            while (!quit)
            {
                Console.Write("get cache: ");
                string demo = Console.ReadLine();
                switch (demo)
                {
                    case "Y": ExecuteCode(CacheTest); break;
                    case "Q":
                        quit = true;
                        break;
                    default:
                        Console.WriteLine("Choose a Word of Y and Q(to quit)");
                        break;
                }
            }
            Console.ReadKey();
        }

        public static void ExecuteCode(Action a)
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            a();

            stopwatch.Stop();
            TimeSpan timespan = stopwatch.Elapsed;

            Console.WriteLine("运行{0}秒", timespan.TotalSeconds);
        }
复制代码

 

出处:http://blog.csdn.net/joyhen/article/details/39990455

posted on   jack_Meng  阅读(3187)  评论(0编辑  收藏  举报

编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek “源神”启动!「GitHub 热点速览」
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩