Asp.net| Cache | performance | site [Introduction]
Asp. NET provides three main forms of caching: page-level output caching, user control-level output caching (or fragment caching), and caching APIs. The advantage of output caching and fragment caching is that it is very easy to implement, and in most cases it is sufficient to use both types of caching. The caching API provides additional flexibility (which is actually quite a lot of flexibility) and can be used to leverage caching at every level of the application. This paper comprehensively introduces the application of these three kinds of caching techniques in each layer of the system.
Of the many features provided by ASP.net, caching support is certainly the most appreciated feature of mine, and I would say there are good reasons for that. Caching has the greatest potential impact on the performance of an application compared to all other features of ASP.net, and with caching and other mechanisms, asp.net developers can accept the extra overhead of building a site with expensive controls, such as a DataGrid, without having to worry about the impact of performance. To maximize caching in your applications, you should consider ways to implement caching at all program levels.
Steve's Caching Tips
? 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 prevent many 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 later when you have time.
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).
Realize
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. 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.
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 might have been optimized for IE, which should be canceled for 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.
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. In addition, menus and other layout elements, especially those that are dynamically generated from the data source, can also be cached in this way.
If you want, you can select the controls you want to cache in the following conditions:
(1) The properties of a control have changed
(2) any page or control state change supported by page-level output caching
Once you have cached some controls, you can share them with the hundreds of pages that you use, and you no longer need to keep separate control cache 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 set the value of the parameter shared to "true", 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 will target the Categorydrop
Downlist each different value of the control, creating a separate cache entry for each page on which the control resides.
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).
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.
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.
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.
There are several things to note about this pattern:
R some values (for example, CacheKey, CacheItem, and cache duration) are defined once and are defined once.
R 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.
The R cache 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.
R 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 R 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.
[Author profile]
Steven A. Smith is a Microsoft ASP. NET's most valuable expert, as Aspalliance.com's president, and also as the owner of the company. He is also the owner and principal lecturer of Aspsmith Ltd (A. NET-centric training company). He has asp.net Developer ' s cookbook and asp.net by example two books, in addition to the MSDN Magazine and Aspnetpro magazine published articles. Every year, Steve talks at several conferences, and he is a member of the Ineta Speaker ' s bureau. Steve has a degree in Business Administration and a BS in computer Science Engineering. If you want to contact Steve, you can send an email to ssmith@aspalliance.com.
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.