Take full advantage of ASP.net's three kinds of caching to improve the performance of the site attention method _ Practical skills

Source: Internet
Author: User
Tags advantage
Asp. NET provides three main forms of caching: page-level output caching, user control-level output caching (or fragment caching), and caching APIs.

Cache as early as possible;
You should implement caching at every level of your application. Add caching support to the data tier, business logic tier, UI, or output layer. Memory is now very cheap-therefore, a great performance improvement can be achieved by implementing caching in the entire application in an intelligent manner.

Page-Level output caching

The simplest form of caching is to keep a copy of the HTML that is sent in response to the request in memory.
To implement the page output cache, simply add a OutputCache directive to the page.

<%@ OutputCache duration= "*" varybyparam= "*"%>

It supports five properties (or parameters), of which two are required.

Duration Required Properties. The time, in seconds, that the page should be cached. Must be a positive integer.

The location of the Location cache. Parameters: Any, Client, downstream, None, server, or ServerAndClient.

VaryByParam Required Properties. The name of the variable in request. None indicates no change. * Used to create a cache for each variant.
Use ";" between variables. are separated.

VaryByHeader changes the cached entry based on the changes in the specified header.

VaryByCustom allows custom changes to be specified in Global.asax (for example, "Browser").

Use a combination of the required duration and VaryByParam options to handle most situations. For example, if your product catalog allows users to view catalog pages based on CategoryID and page variables, you can cache the product catalog for a period of time with the VaryByParam parameter value of "Categoryid;page" (if the product is not always changing, an hour is acceptable, Therefore, the duration is 3,600 seconds). This creates a separate cache entry for each catalog page of each kind. Each entry will be maintained for one hours from its first request.

Example: VaryByCustom is used to support browser customization

In order for each browser to have a separate cache entry, the VaryByCustom value can be set to "browser". This feature is already built into the cache module, and a separate page cache version is inserted for each browser name and major version.

<%@ OutputCache duration= varybyparam= "None" varybycustom= "Browser"%>



Fragment caching, user control output caching

Fragment caching uses the same syntax as page-level output caching, but it applies to user controls (. ascx files) instead of Web Forms.

The user control also supports a property named VaryByControl, which changes the cache of the control based on the value of the server control in the. ascx file. If you specify a VaryByControl, you can omit VaryByParam. If all pages use the same user control, you can set the value of the parameter shared to "true".

<%@ OutputCache duration= "*" varybyparam= "*"%>
Cache the user control for 60 seconds and create a separate cache for each change to the request.

<%@ OutputCache duration= varybyparam= "None" Varybycontrol= "Mycontrolname"%>
The user control is cached for 60 seconds and a separate cache is created for each of the different values of the Downlist control for "Mycontrolname".

<%@ OutputCache duration= varybyparam= "None" varybycustom= "Browser" shared= "true"%>
Caches the user control for 60 seconds and creates a cache entry for each browser name and major version. Each page share that references this user control (as long as all pages refer to the control with the same ID).



Caching APIs, using cache objects

Page-level and user-control-level output caching is indeed a way to quickly and easily improve site performance, but in ASP.net, the true flexibility and power of caching is provided through the cache object. With the cache object, you can store any serializable data objects, based on a combination of one or more dependencies, to control how the cached entries expire. These dependencies can include the time elapsed since an object was cached, the time elapsed since an object was last accessed, changes to a file or folder, and changes to other cached objects, which can also include changes to a particular table in the database after a slight processing.

Storing data in cache

The easiest way to store data in the cache is to use a key to assign it a value, just like a Hashtable or Dictionary object:

cache["key"] = "value";

This approach stores the item in the cache without any dependencies, so it does not expire unless the caching engine deletes it in order to provide space for other cached data. To include specific cache dependencies, you can use the Add () or Insert () method. Each of these methods has several overloads. The only difference between add () and insert () is that add () returns a reference to the cached object, and the insert () does not return a value (null in C # and a sub in VB).

Example

Cache.Insert ("Key", Myxmlfiledata, new
System.Web.Caching.CacheDependency (Server.MapPath ("Users.xml"));

The example inserts the XML data from the file into the cache without having to read it from the file at a later request. The role of CacheDependency is to ensure that the cache expires immediately after the file changes so that the latest data can be extracted from the file and cached again. If the cached data is from several files, you can also specify an array of file names.

Cache.Insert ("Dependentkey", Mydependentdata, new
System.Web.Caching.CacheDependency (new string[] {}, new string[]
{"Key"}));

The example inserts a second block of data with the key value "key" (depending on whether the first block of data exists). If a key named "key" does not exist in the cache, or if the object associated with the key has expired or been updated, the cache entry for "Dependentkey" expires.

Cache.Insert ("Key", Mytimesensitivedata, NULL,
DateTime.Now.AddMinutes (1), TimeSpan.Zero);

Absolute expiration: This example caches data that is affected by time by one minute and the cache expires after one minute. Note that absolute expiration and scrolling expiration (see below) cannot be used together.

Cache.Insert ("Key", Myfrequentlyaccesseddata, NULL,
System.Web.Caching.Cache.NoAbsoluteExpiration,
Timespan.fromminutes (1));

Dynamic scrolling Expiration: This example caches some frequently used data. The data will remain in the cache until the data has not been referenced for a minute. Note that dynamic scrolling expiration and absolute expiration cannot be used together.

More options

In addition to the dependencies mentioned above, we can also specify the priority of the item (in descending order, high, notremovable, They are defined in the System.Web.Caching.CacheItemPriority enumeration and CacheItemRemovedCallback functions that are called when the objects in the cache expire. Most of the time, the default priority is sufficient-the caching engine completes the task and processes the cached memory management. The CacheItemRemovedCallback option takes into account some interesting possibilities, but it is rarely used. However, to illustrate this method, I will provide an example of its use:

CacheItemRemovedCallback sample

System.Web.Caching.CacheItemRemovedCallback callback = new System.Web.Caching.CacheItemRemovedCallback (onremove);
Cache.Insert ("Key", Myfile,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.Default, callback);
. . .
public static void OnRemove (string key, Object CacheItem,
System.Web.Caching.CacheItemRemovedReason reason)
{
Appendlog ("The cached value with key '" + key +
"' was removed from the cache. Reason: "+
Reason. ToString ());
}

The example uses any logic defined in the Appendlog () method to record the reason for the expiration of the data in the cache. You can determine whether the cache is being used effectively or if you may need to increase the memory on the server by recording the items when you delete them from the cache and by recording the reasons for the deletion. Note that callback is a static (shared) method in VB, and the reason for this is that if you do not use it, an instance of the class that holds the callback function will remain in memory to support the callback (not necessary for the Static/shared method).

This feature has a potential usefulness-refreshing cached data in the background so that users never have to wait for data to be populated, but the data remains relatively new. In practice, however, this attribute does not apply to the current version of the cache API because the callback is not triggered or not completed until the cached item is deleted from the cache. As a result, users will frequently issue requests that attempt to access the cached value, and then find that the cached value is empty and have to wait for the cached value to be filled in again. I want to see an additional callback in the future ASP.net version, which can be called cacheditemexpiredbut

Notremovedcallback, if the callback is defined, execution must be completed before the cache entry is deleted.

Cached data Reference mode

Whenever we try to access data in the cache, we should take into account the fact that the data may not be in the cache anymore. Therefore, the following pattern should be universally applicable to your access to cached data. In this case, we assume that the cached data is a datasheet.

Public DataTable GetCustomers (bool Bypasscache)
{
String cachekey = "CustomersDataTable";
Object CacheItem = Cache[cachekey] as DataTable;
if ((Bypasscache) | | (CacheItem = null))
{
CacheItem = Getcustomersfromdatasource ();
Cache.Insert (CacheKey, CacheItem, NULL,
DateTime.Now.AddSeconds (Getcachesecondsfromconfig (CacheKey), TimeSpan.Zero);
}
Return (DataTable) CacheItem;
}

There are several things to note about this pattern:

1 Some values (for example, CacheKey, CacheItem, and cache duration) are defined once and are defined once.

2 You can skip caching as needed-for example, when registering a new customer and redirecting to the customer list, it may be best to skip the cache and repopulate the cache with the latest data, including the newly inserted customer.

3) caching can only be accessed once. This approach improves performance and ensures that nullreferenceexceptions does not occur because the item existed the first time it was checked, but it expired before the second check.

4 The mode uses a strong type check. The "as" operator in C # attempts to convert an object to a type, and if it fails or is empty, only null (empty) is returned.

5 The duration is stored in the configuration file. Ideally, all cache dependencies, whether file-based, or based on time, or other types of dependencies, should be stored in the configuration file so that you can make changes and easily measure performance. I also recommend that you specify the default cache duration, and let the Getcachesecondsfromconfig () method use the default duration if you do not specify a duration for the cachekey you are using.

The code example associated with this article (Cacheddemo.msi, see the sample CD for this book) is a helper class that handles all of the above and can only write one or two lines of code to access the cached data.

Summary

Caching can greatly improve the performance of your application, so you should consider it when designing your application and performing performance testing on your application. Applications will always benefit more or less from caching, and some applications are more appropriate to use caching than other applications. A deep understanding of the caching options provided by ASP.net is an important skill that any asp.net developer should master.

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.