简体   繁体   中英

System.Web.Caching.Cache in ASP.NET

I just discovered System.Web.Caching.Cache used in a project that I am working on and I am having a hard time finding more information on it.

My question is how this cache is persisted? Is it client-side (similar to ViewState ), server-side ( Session )? Entirely different?

Example:

protected string FileContent 
{ 
    get 
    { 
        return Cache[FILE_UPLOAD_KEY + Id] as string ?? GetFileUpload(); 
    } 
}

It's a server-side, application-wide cache.

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object. ( Cache Class, MSDN )

It grants the ability to set time limits and so forth on cached objects. And it doesn't promise the object will be there when you need it again. It keeps items in cache only so long as there is sufficient memory to do so.

So, it's not intended for passing objects between page views (use ViewState or Session for that) or controls (use Items for that). It's intended to cache global objects (accessible in any request from all clients) that are expensive to build.

It's persisted at the server, and it's global across sessions, like Application . So when you set a value in the Cache , it's available to all users until it expires.

EDIT

The example you've got probably isn't quite right (unless GetFileUpload() actually writes to the cache). Generally your calls to cache look something like:

string GetSomeStringFromCache()
{
    string someString = Cache[SomeKey] as string;
    if (someString == null)
    {
        someString = GetStringUsingSomeExpensiveFunction();
        Cache.Add(SomeKey, someString, /*a bunch of other parameters*/);
    }
    return someString;
}

This will put it in the Cache if it's not already there, but if it is, it will just use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM