elaborate asp.net cache and its advanced usage--server-side Caching __.net

Source: Internet
Author: User
Tags httpcontext instance method

Read the directory start cache basic use cache definition caching common usage cache class dependencies-dependencies of expiration cache entries for items-dependent dependencies on other cache entries cache entries-removal of priority cache entries for file-dependent cache entries Smart use Cache entry Removal Notification implementation of "deferred operation" skillfully using cache entry removal notification implementation of "Automatic load Profile" file monitoring technology selection coexistence of various caching schemes

Many people who have done program performance optimizations, or who are concerned with process performance, should have used all kinds of caching techniques. And the cache I'm talking about today is specifically about the cache of ASP.net, and we can use the cache that the Httpruntime.cache accesses, not the other caching techniques.

I used to briefly mention it in my "asp.net core object" blog, and today I'm going to write a blog about it, specifically to talk about it, because it's so important. In this blog, I will not only introduce some of its common usage, but also introduce some of its advanced usage. At the end of the previous blog, "Reading and writing config files in. Net", I left you with a question that I will give you in this blog today that I think is the perfect answer.

The "deferred operations" method mentioned in this article (e.g., deferred merge write database) is a summary of my experience and I hope we can enjoy this idea. Back to the top cache for basic use

Mention cache, have to say it's main function: Improve program performance.
Asp. NET is a kind of dynamic page technology, with ASP.net technology made out of the Web pages are almost dynamic, the so-called dynamic refers to: the content of the page will be with different users or continuously updated data, and show different results. Since it is dynamic, where does the content of these developments come from? I think most of the sites have their own data source, the program by accessing the data source to get the data required by the page, and then according to some business rules of calculation processing, finally become suitable for the content of the page display.

Because this kind of dynamic page technology usually needs to obtain the data from the data source, and passes some computational logic, finally becomes some HTML code to send to the client to display. And these computational processes are clearly costing. These processing costs are most directly manifested as impacting the responsiveness of the server, especially when data processing becomes complex and access is large. On the other hand, some data is not always changing, and if we can cache the final results (including page output) of some infrequently changing data, we can significantly improve the performance of the program, which is the most common and important use of caching. This is why, when it comes to performance optimization, caching is generally the first reason. The asp.net cache that I'm going to talk about today is also a technique to implement this caching. However, it has other features, some of which are not available in other caching technologies.

Back to the top cache definition

Before introducing the use of cache, let's look at the definition of cache: (Note: I overlooked some insignificant members)

Asp. NET in order to facilitate our access to the cache, in the HttpRuntime class added a static property cache, so that we can use the cache in any place function. And, ASP. NET added two "shortcuts" to it: Page.cache, Httpcontext.cache, we can also access Httpruntime.cache through these two objects, note: These three are accessing the same object. Page.cache visited Httpcontext.cache, while Httpcontext.cache directly accessed Httpruntime.cache back to the top Cache common usage

Generally, when we use cache, there are usually only two actions: Read, write.
To get a cache entry from the cache, we can call the Cache.get (key) method, and to put an object into the cache, we can call add, insert method. However, ADD, the Insert method has many parameters, sometimes we just want to simply put in the cache, all accept the default value, then you can also call its default indexer, let's take a look at how this indexer works:

public Object This[string key]
{get {return this
        . Get (key);
    }
    Set
    {this
        . Insert (key, value);
    }

As you can see, the read cache is actually calling the Get method, while the write cache is the simplest overloaded version that invokes the Insert method.

Note: The Add method can also place an object in the cache, which has 7 parameters, and the insert has an overloaded version similar to the signature, which has a similar function: adding the specified item to the System.Web.Caching.Cache object, which has a dependency , expiration, and priority policies, and a delegate that can be used to notify the application when an insert item is removed from the Cache. However, they have a small difference: when the cached item to be added is already in the cache, the insert overwrites the original cache item, and add does not modify the original cache entry.

In other words: If you want a cached item to be cached and not modified again, calling add does prevent subsequent modifications. When you invoke the Insert method, you will always overwrite the existing item (even if it was previously called add).

From another point of view, the effect of add is more like static readonly behavior, and the effect of inserts is static behavior.
Note: I'm just saying "like", in fact they have a more flexible use than the normal static members.

Because the cache entry allows us to access it anytime, it does look like a static member, but they have more advanced features such as cache expiration (absolute expiration, sliding expiration), cache dependencies (dependent files, dependent on other cache entries), removal of priority, notification before and after cache removal, and so on. I will introduce these four characteristics separately. Back to the top cache class features

The cache class has a very rare advantage, with the words on MSDN:

This type is thread-safe.

Why is this a rare advantage? Because most classes are implemented in. NET, the only way to ensure a static type is thread-safe, regardless of whether the instance method is thread safe. It's a basic one, too. NET design specification principle.
For those types, MSDN is usually described in this way:

Members of this type of public static (Shared in Visual Basic) are thread-safe. However, there is no guarantee that any instance members are thread safe.

So, this means that we can read and write anywhere in the cache without worrying about the data synchronization problem of cache data in a multithreaded environment. In multithreaded programming, the most complex problem is the synchronization of data, and cache has solved these problems for us.

But I want to remind you: ASP.net itself is a multithreaded programming model, all requests are handled by thread pool threads. Usually, we in the multithreaded environment in order to solve the problem of data synchronization, is generally the use of locks to ensure data synchronization, naturally, ASP. NET is no exception, in order to solve the problem of data synchronization, internal is also adopted a lock.

Here, perhaps some people would think: since only a static instance of the cache, then this lock will not affect concurrency.
The answer is yes, there is a certain degree of lock will affect the concurrency, it is no way to do things.
However, ASP. NET in the implementation of cache, will be based on the number of CPUs to create a number of cache containers, as far as possible to reduce conflicts, the following is the core process of cache creation:

Internal static cacheinternal Create () {cacheinternal internal2;
    int numsinglecaches = 0;
        if (numsinglecaches = = 0) {UINT Numprocesscpus = (UINT) Systeminfo.getnumprocesscpus ();
        Numsinglecaches = 1; for (Numprocesscpus = 1; numprocesscpus > 0; numprocesscpus = Numprocesscpus >> 1) {Numsinglecache
        s = numsinglecaches << 1;
    } Cachecommon Cachecommon = new Cachecommon ();
    if (numsinglecaches = = 1) {Internal2 = new Cachesingle (Cachecommon, NULL, 0);
    else {internal2 = new Cachemultiple (Cachecommon, numsinglecaches);
    } cachecommon.setcacheinternal (Internal2);
    Cachecommon.resetfromconfigsettings ();
return internal2; }

Description: Cacheinternal is an internal packaging class, the cache of many operations to be done by it.

In the above code, the Numsinglecaches calculation process is important, if the code above is not easy to understand, then look at my sample code below:

static void Main ()
{for
    (uint i = 1; I <= i++)
        showcount (i);            
}
static void Showcount (UINT Numprocesscpus)
{
    int numsinglecaches = 1;
    for (Numprocesscpus = 1; numprocesscpus > 0; numprocesscpus = Numprocesscpus >> 1) {
        numsinglecaches = Nums Inglecaches << 1;
    }
    Console.Write (numsinglecaches + ",");
}

The program will output:

1,2,4,4,8,8,8,8,16,16,16,16,16,16,16,16,32,32,32,32

The Cachemultiple constructor is as follows:

Internal Cachemultiple (Cachecommon cachecommon, int numsinglecaches): Base (Cachecommon)
{
    this._ Cacheindexmask = numSingleCaches-1;
    This._caches = new Cachesingle[numsinglecaches];
    for (int i = 0; i < numsinglecaches i++)
    {
        This._caches[i] = new Cachesingle (Cachecommon, this, i);
    }
}

Now you should understand: Cachesingle is actually a cache container used internally by ASP.net, which creates multiple cache containers when multiple CPUs.
When writing, how does it locate these containers? Please continue to look at the code:

Internal Cachesingle getcachesingle (int hashcode)
{
    hashcode = Math.Abs (hashcode);
    int index = hashcode & this._cacheindexmask;
    return this._caches[index];
}

Description: The hashcode in the parameter is the Key.gethashcode () that calls us directly, GetHashCode is defined by the object class.

So, from this point of view, although ASP.net cache has only one httpruntime.cache static member, its interior may contain multiple cache containers, a design that can reduce the concurrent impact to some extent.

No matter how designed, in a multithreaded environment, sharing a container, conflict is unavoidable. If you just want to simply cache some of the data and do not need many of the advanced features of the cache, then you can consider using no cache. For example, you can create a static instance of dictionary or Hashtable, which can also do some basic caching, but I would like to remind you that you want to handle the data synchronization problem of multithreaded access data yourself.
By the way: hashtable.synchronized (New Hashtable ()) is also a thread-safe collection, and if you want to be simple, consider it.

Next, let's take a look at the advanced features of the cache, which are dictionary or Hashtable. Returns the expiration time of the top cache entry

Asp. NET supports expiration policies for two kinds of cache entries: absolute expiration and sliding expiration.
1. Absolute expiration, this is easy to understand: that is, in the cache when cached, specify a specific time. When the time reaches the specified time, the cache entry is automatically removed from the cache.
2. Sliding expiration: Some cache entries, we may only want to keep it in the cache when a user accesses it, and then remove it only when the user no longer accesses the cache entry, which can optimize the use of the memory because it guarantees that the cached content is "hot". Not all of the operating system's memory and the disk's cache are designed this way. And this very useful feature, cache is also ready for us, as long as the cache entry into the cache, specify a sliding expiration time can be achieved.

The above two options correspond to add, DateTime absoluteexpiration in the Insert method, TimeSpan slidingexpiration these two parameters.
Note: These two parameters are used in pairs, but they cannot be specified as a valid value and can be valid for at most one parameter value. When you do not use another parameter item, define two static readonly field assignments with the cache class.

These two parameters are relatively simple, I will not say more, just say: If all use noxxxxx these two options, then the cache entries are kept in the cache. (may also be removed)

Back to top cache entry dependencies-dependent on other cache entries

asp.net cache has a very powerful function, that is caching dependencies. One cache entry can depend on another cache entry. The following sample code creates two cache entries and has dependencies between them. First, look at the page code:

<body>
    <p>key1 Cache content: <%= httpruntime.cache["Key1"]%></p> 

Page Background code:

public partial class CacheDependencyDemo:System.Web.UI.Page {[Submitmethod (autoredirect=true)] private void Se

        Tkey1cache () {Setkey2cache (); CacheDependency dep = new CacheDependency (null, new string 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.