Asp. NET caching methods and best practices _ practical Tips

Source: Internet
Author: User
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.
   caching can cover up a lot of mistakes.   
Caching is a way to get "good enough" performance without a lot of time and analysis. Again, the emphasis here memory is now very cheap, so if you can get the performance you need by caching the output for 30 seconds instead of trying to optimize the code or the database for a whole day or even a week, you will definitely choose to cache the solution (assuming you can accept 30 seconds of old data). Caching is one of those features that uses 20% to get 80% returns, so to improve performance, you should think of caching first. However, if the design is bad and the end result is likely to have undesirable consequences, you should, of course, design the application as well as possible. But if you just need to get high enough performance immediately, caching is your best option, and you can redesign your application as soon as you have time later.
   page-Level output caching
As the simplest form of caching, the output cache retains only the copy of the HTML that is sent in response to the request in memory. Subsequent requests will provide cached output until the cache expires, so that performance can be significantly improved (depending on how much overhead is required to create the original page output-the output of the send cache is always fast and relatively stable).
   Implement   
To implement the page output cache, simply add a OutputCache directive to the page.
<%@ OutputCache duration= "*" varybyparam= "*"%>
As with other page directives, the directive should appear at the top of the ASPX page, before any output. 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.
Location
Specifies where the output should be cached. If you want to specify this parameter, you must be one of the following: Any, Client, downstream, None, Server, or serverandclient.
VaryByParam
Required Properties. The name of the variable in Request, which should produce a separate cache entry. "None" indicates no change. The "*" can be used to create a new cache entry for each variant array. separated by ";" between variables.
VaryByHeader
Changes the cached entry based on the changes in the specified header.
VaryByCustom
Allows you to specify a custom change (for example, "Browser") in Global.asax.
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.
VaryByHeader and VaryByCustom are primarily used to customize the appearance or content of a page based on the client accessing the page. The same URL may need to render output for both the browser and the mobile client, so different content versions are cached for different clients. Alternatively, the page may have been optimized for IE, but it needs to be able to completely reduce optimizations (rather than just damaging pages) against Netscape or Opera. The latter example is very common, and we will provide an example that shows how to achieve this goal:

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

Caching an entire page is usually not feasible, because some parts of the page are customized for the user. However, other parts of the page are common to the entire application. These sections are best used for caching with fragment caching and user controls. Menus and other layout elements, especially those that are dynamically generated from the data source, should also be cached in this way. If you want, you can configure the cached control to change based on changes to its controls (or other properties) or any other changes supported by the page-level output cache. Hundreds of pages that use the same set of controls can also share cached entries for those controls, rather than reserving separate cached versions for each page.

Realize

Fragment caching uses the same syntax as page-level output caching, but it applies to user controls (. ascx files) instead of Web forms (. aspx files). In addition to the Location property, the user control is also supported for all properties that OutputCache supports on Web forms. The user control also supports the OutputCache property named VaryByControl, which changes the cache of the control based on the value of the user control, which is typically a member of a control on the page, for example, DropDownList. If you specify a VaryByControl, you can omit VaryByParam. Finally, by default, each user control on each page is cached separately. However, if a user control does not change with the page in the application and the same name is used on all pages, you can apply the shared= "true" argument, which will make the cached version of the user control available to all pages that reference the control.

Example

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

The example caches the user control for 60 seconds and creates a separate cache entry for each change to the query string, for each page that contains the control.

<%@ OutputCache duration= varybyparam= "None"
Varybycontrol= "Categorydropdownlist"%>

The example caches the user control for 60 seconds and creates a separate cache entry for each distinct value of the categorydropdownlist control, and for each page that contains the control.
 
<%@ OutputCache duration= varybyparam= "None" varybycustom= "Browser"
Shared= "True%>

Finally, the example caches the user control for 60 seconds and creates a cache entry for each browser name and major version. The cached entries for each browser are then shared by all pages that reference the user control (as long as all pages refer to the control with the same ID).

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 the item was cached, the time elapsed since the item was last accessed, changes to files and/or folders, and changes to other cached items, 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 item 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 sliding expiration (see below) cannot be used together.
Copy Code code as follows:

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

Sliding 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 sliding 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 items (in descending, high, notremovable, which are defined in the System.Web.Caching.CacheItemPriority enumeration) and when the items in the cache expire. CacheItemRemovedCallback function. 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
 
Copy Code code as follows:

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 the Appendlog () method, which is not discussed here, and any logic defined in writing Entries to Event Logs is used 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, called Cacheditemexpiredbutnotremovedcallback, in a future ASP.net version, and if the callback is defined, execution must be done 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.
Copy Code code as follows:

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:   
Some values (for example, CacheKey, CacheItem, and cache duration) are defined once and are defined once.
You can skip caching as needed-for example, after 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.
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.
This mode uses strong type checking. 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.
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 relevant code example is a helper class that handles all of the above, but allows access to cached data through one or two lines of code. Please download Cachedemos.msi.
   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.