【转载】HttpContext.Cache和HttpRuntime.Cache

原文地址:HttpRuntime.Cache vs. HttpContext.Current.Cache  HttpContext.Cache和HttpRuntime.Cache   HttpContext.Current.Cache vs. HttpRuntime.Cache 

 

 

HttpRuntime.Cache vs. HttpContext.Current.Cache

Here's a development tip I came across on one of the ASP.NET discussion lists I'm on, at AspAdvice.com.

Original question:
Is there a difference in accessing the Cache of an application when calling HttpRuntime.Cache vs. HttpContext.Current.Cache?  I "think" I remember reading about a difference in the two a few years ago, but I don't remember the specifics.  This assumes that I am within a web application.

Answer from Rob Howard:
HttpRuntime.Cache is the recommended technique.

Calling the HttpContext does some additional look-ups as it has to resolve the current context relative to the running thread.

I use HttpContext.Current in a lot of the code I write too; but touching it as little as possible. Rather than calling HttpContext.Current repeatedly it's best to hang onto a reference and pass it around (when possible).

If you're in a component HttpRuntime.Cache is still the recommendation.

That said... the differences in performance are not going to be noticeable in 99% of the applications many of us write. The cases where it is going to matter is the 1% (or less) where you're trying to squeeze every last drop of performance out of you system. But this is a *minor* performance tweak, e.g. eliminating a database call, web service call or other out-of-process call in the application is definitely a better place to spend optimizing code.

For example, if you have 5 database calls in a particular code path reducing (or even optimizing) the queries is a much better use of time.

So yes, HttpRuntime.Cache is recommended but likely won't make a difference in most applications.

Another reply from James Shaw at CoverYourASP.NET:
I discovered another *great* reason to use HttpRuntime too, when writing my unit tests - HttpRuntime.Cache is always available, even in console apps like nunit!

http://www.coveryourasp.net/UnittestingandCaching

I never use HttpContext anymore, even in class libraries.

原文地址: HttpContext.Cache和HttpRuntime.Cache   HttpContext.Current.Cache vs. HttpRuntime.Cache 

 

Asp.Net中可以方便的使用缓存,对于Cache,一般有两种方式调用:HttpContext.Cache和HttpRuntime.Cache。那么这两种Cache有什么区别呢?

先来看看Msdn上的注释:
HttpRuntime.Cache:获取当前应用程序的 Cache。
HttpContext.Cache:为当前 HTTP 请求获取 Cache 对象。

那么是不是说对于HttpRuntime.Cache就是应用程序级,而HttpContext.Cache则是针对每个用户的呢?NO,而实际上,两者调用的是同一个对象。他们的区别仅仅在于调用方式不一样(就我所知)。

事实胜过雄辩,写个例子来证实一下(限于篇幅仅贴出关键代码,完整代码见附件WebDemo.rar):

 
 
ExpandedBlockStart.gif ContractedBlock.gif /**/ /// <summary> /// 通过HttpRuntime.Cache的方式来保存Cache /// </summary> private void btnHttpRuntimeCacheSave_Click( object sender, System.EventArgs e) ExpandedBlockStart.gifContractedBlock.gif ... { HttpRuntime.Cache.Insert(cacheKey, cacheValue, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero); } ExpandedBlockStart.gifContractedBlock.gif /**/ /// <summary> /// 通过HttpRuntime.Cache的方式来读取Cache /// </summary> private void btnHttpRuntimeCacheLoad_Click( object sender, System.EventArgs e) ExpandedBlockStart.gifContractedBlock.gif ... { if (HttpRuntime.Cache[cacheKey] == null) ExpandedSubBlockStart.gifContractedSubBlock.gif...{ cacheContent = "No Cache"; } else ExpandedSubBlockStart.gifContractedSubBlock.gif...{ cacheContent = (string)HttpRuntime.Cache[cacheKey]; } lblCacheContent.Text = cacheContent; } ExpandedBlockStart.gifContractedBlock.gif /**/ /// <summary> /// 通过HttpContext.Cache的方式来保存Cache /// </summary> private void btnHttpContextCacheSave_Click( object sender, System.EventArgs e) ExpandedBlockStart.gifContractedBlock.gif ... { HttpContext.Current.Cache.Insert(cacheKey, cacheValue, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero); } ExpandedBlockStart.gifContractedBlock.gif /**/ /// <summary> /// 通过HttpContext.Cache的方式来读取Cache /// </summary> private void btnHttpContextCacheLoad_Click( object sender, System.EventArgs e) ExpandedBlockStart.gifContractedBlock.gif ... { if (HttpContext.Current.Cache[cacheKey] == null) ExpandedSubBlockStart.gifContractedSubBlock.gif...{ cacheContent = "No Cache"; } else ExpandedSubBlockStart.gifContractedSubBlock.gif...{ cacheContent = (string)HttpContext.Current.Cache[cacheKey]; } lblCacheContent.Text = cacheContent; }
  1. 通过这个例子可以很容易证明:
  2. HttpContext.Cache保存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以读取。
  3. HttpRuntime.Cache保存的Cache,HttpContext.Cache和HttpRuntime.Cache都可以读取。
  4. 无论是哪个用户通过什么方式对Cache的改变,其他用户无论用什么方式读取的Cache内容也会随之变。


原文地址:  HttpContext.Current.Cache vs. HttpRuntime.Cache 

.NET中Cache有两种调用方式:HttpContext.Current.Cache 和 HttpRuntime.Cache,这两种方式有什么区别呢?我们先看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应用。

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

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

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


            System.Web.HttpContext httpContext 
= System.Web.HttpContext.Current;
            
if (httpContext == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                Console.WriteLine(
"HttpContext object is null in Console Project");
            }

            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                System.Web.Caching.Cache httpContextCache 
= httpContext.Cache;
                httpContextCache.Insert(
"httpContextCache""I am stored in HttpRuntime.Cache");
                
if (httpContextCache == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值