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 == ? new TimeSpan(, , ) : new TimeSpan(, durationMin, );
//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(, , );
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

上一篇:MySQL强人“锁”难《死磕MySQL系列 三》


下一篇:mysql小白系列_10 mysql主从复制原理