首页 > 系统服务 > 详细

Page.Cache

时间:2019-04-24 15:43:20      阅读:156      评论:0      收藏:0      [点我收藏+]

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.cache?view=netframework-4.8

Gets the Cache object associated with the application in which the page resides.

 

An application‘s Cache object allows you to store and retrieve arbitrary data on subsequent requests. The cache is not specifically associated with a page or user session. It is used primarily to enhance application performance. For more information, see Caching Application Data. For more information on the difference between application caching and page output caching, see ASP.NET Caching Overview.

 

Page.Cache vs. HttpContext.Current.Cache

 

There is no difference, the former uses the current page instance and it‘s Cache property, the latter uses the static approach via HttpContext.Current.Cache which would work also in a static method without page instance.

Both are referring to the same application cache.

So you can get the Cache via Page, for example in Page_Load:

protected void Page_load(Object sender, EventArgs e)
{
    System.Web.Caching.Cache cache = this.Cache;
}

or in a static method (which is used in a HttpContext) via HttpContext.Current:

static void Foo()
{
    var context = HttpContext.Current;
    if (context != null)
    {
        System.Web.Caching.Cache cache = context.Cache;
    }
}

 

Difference between HttpRuntime.Cache and HttpContext.Current.Cache?

I find following detail from http://theengineroom.provoke.co.nz/archive/2007/04/27/caching-using-httpruntime-cache.aspx

For caching I looked into using HttpContext.Current.Cache but after reading other blogs I found that caching using HttpContext uses HttpRuntime.Cache to do the actual caching. The advantage of using HttpRuntime directly is that it is always available, for example, in Console applications and in Unit tests.

Using HttpRuntime.Cache is simple. Objects can be stored in the cache and are indexed by a string. Along with a key and the object to cache the other important parameter is the expiry time. This parameter sets the time before the object is dropped from the cache.

Here is good link for you.

Another good resource.

 

Is the HttpContext.Current.Cache available to all sessions

HttpContext.Current is available to all pages, but not necessarily to all threads. If you try to use it inside a background thread, ThreadPool delegate, async call (using an ASP.NET Async page), etc., you‘ll end up with a NullReferenceException.

If you need to get access to the cache from library classes, i.e. classes that don‘t have knowledge of the current request, you should use HttpRuntime.Cache instead. This is more reliable because it doesn‘t depend on an HttpContext.

 

扩展阅读

Cache Class

Caching Application Data

 

Page.Cache

原文:https://www.cnblogs.com/chucklu/p/10762627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!