【简】
In many features provided by ASP.NET, cache support is undoubtedly my most appreciated, I said that it is of course full reason. Compared to all other features of ASP.NET, the cache has the greatest potential impact on the performance of the application, using cache and other mechanisms, ASP.NET developers can accept the use of high-cost controls (for example, DataGrid) build sites. Additional expenses don't worry that performance will be too much affected. To maximize the cache in your application, you should consider how cache is achieved at all program levels.
Implementation To implement the page output cache, just add an OutputCache instruction to the page. <% @ OutputCache Duration = "60" VaryByParam = "*"%> As with other page instructions, the instruction should appear at the top of the ASPX page, that is, before any output. It supports five attributes (or parameters), two of which are required. Duration Required attributes. The page should be cached, in seconds. Must be positive integers. Location Specifies the location where the output should be cached. If you want to specify this parameter, you must be one of the following options: Any, Client, DownStream, None, Server, or ServerandClient. VaryByParam is required. The name of the variable in the request, these variable names should generate a separate cache entry. "None" means there is no change. "*" Can be used to create a new cache entry for each different variable array. The variable is separated by ";". VarybyHeader changes Cache entries based on changes in the designated header. Varybycustom allows custom changes in Global.asax (for example, "Browser"). Most of the cases can be handled with a combination of required Duration and VarybyParam options. For example, if your product catalog allows users to view directory pages based on CategoryID and page variables, you can use the parameter value "categoryid; page" to cache the product directory for a while (if the product is not changed at any time, one hour can still Accepted, therefore, the duration is 3,600 seconds). This will create a separate cache entry for each directory page of each species. Each entry will be within an hour from its first request. VarybyHeader and VarybyCustom are used to customize the appearance or content of the page based on the client access page. The same URL may need to be output to the browser and mobile phone client, so you need to cache different content versions for different clients. Alternatively, the page may have been optimized for IE, but it is necessary to completely reduce optimization for Netscape or Opera (not just damaged pages). The latter example is very common, we will provide an example of how to implement this goal: Example: VarybyCustom is used to support browser to customize to make each browser have a separate cache entry, VarybyCustom's value can be set to "Browser" . This feature has been built into the cache module and will insert a separate page cache version for each browser name and the main version. <% @ OutputCache Duration = "60" VarybyParam = "None" VaryByCustom = "Browser"%> Cache, user control output cache cache the entire page is usually not feasible, because some parts of the page are customized for users. However, other parts of the page are all the entire application. These parts are best suited to cache segment cache and user controls. Menu and other layout elements, especially those dynamically generated from the data source, should also be cached in this way.
If desired, the cache control can be configured to change any other variation that changes its control (or other attribute) or any other variation supported by the page level output cache. With hundreds of pages that use the same set of controls, you can also share the cache entries for those controls, rather than retain a separate cache version for each page.
Realizing the syntax used by the cloc cache is the same as the page-level output cache, but it is applied to the user control (.ascx file) instead of the web form (.aspx file). In addition to the location attribute, all properties supported on the web form are also supported for all attributes supported on the web form. The user control also supports the OutputCache property called VaryByControl, which changes the control of the control based on the value of the user control (usually the control on the page, for example, DropDownList). If VarybyControl is specified, VaryByParam can be omitted. Finally, by default, each user control on each page is individually cached. However, if a user control does not change with the page in the application, the same name can be applied in all pages, which will apply the Shared = "True" parameter, which will enable the cache version of the user control for all the references to the control. use. Example <% @ OutputCache Duration = "60" VaryByParam = "*"> This example will cache the user control 60 seconds and will create a separate cache entry for each change in the query string. . <% @ Outputcache duration = "60" VarybyParam = "none" VarybyControl = "categoryDropdownList"%> This example will cache the user control 60 seconds and will target each page of this control for each of the CategoryDropDownList controls. Create a separate cache entry. <% @ Outputcache duration = "60" VarybyParam = "none" VarybyCustom = "Browser" Shared = "True%> Finally, this example will cache the user control 60 seconds and create a cache for each browser name and the main versions. Items. Then, the cache entry for each browser will be shared by all pages referenced this user control (as long as all pages are referenced by the same ID). The page level and user control level output cache is indeed a quick Simplely increase the method of the site performance, but in ASP.NET, the true flexibility and powerful function of the cache is provided through the cache object. Use the Cache object, you can store any sequentially-sequential data objects based on one or more A combination of dependencies to control the way caclet entries expire. These dependencies can include time since the item is cached, since the time passed by the item, the time after the time passed, the file and / or folder change and pair Other cache items can also include changes to a specific table in the database after slightly processing. The easiest way to store data in cache in cache is to assign values to its assignment, like HashTable or Dictionary. Object is the same: cache ["key"] = "value"; this approach will be stored in the cache, without any dependencies, so it does not expire, unless the cache engine will provide space to other cache data It deletes. To include a specific cache dependency, use the add () or insert () method.
Each method has several overloads. The only difference between add () and INSERT () is that add () returns a reference to the cached object, and INSERT () does not return a value (empty in C #, in VB is SUB). Example cache.inserta, new system.web.caching.cachedependency (server.mAppath)); This example can insert an XML data in the file into the cache, no need to request later Read from the file. The role of Cachedependency is to ensure that the cache is expired immediately after file changes so that the latest data can be extracted from the file and re-cached. If the cached data comes from a number of files, you can specify an array of file names. Cache.insert ("DependentKey", MyDependentData, New System.Web.Caching.cached "{} (new string" {}, new string [] {"key"}))); this example can be inserted into the key value "Key" Two data blocks (depending on whether there is a first data block). If there is no key called "Key" in the cache, or if the item associated with the key has expired or updated, "DependentKey" cache entries will expire. Cache.Insert ("Key", MyTimeSensitiveData, Null, DateTime.now.addminutes (1), Timespan.zero; absolute expiration: This example will cache data about time a minute, after a minute, the cache will go period. Note that absolute expiration and sliding expire (see below) cannot be used together. Cache.insert ("Key", MyFrequentlyAccesseddata, null, system.Web.caching.cache.noabsoluteExpiration, Timespan.Fromminutes (1)); Sliding expiration: This example will cache some frequently used data. The data will remain in the cache, unless the data has not been referenced for one minute. Note that sliding expires 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 turn, high, notremovable, which is defined in System.Web.Caching.CacheItemPriority enumeration) and when the items in the cache CacheItemRemoveDCallback function called during expiration. Most of the time, the default priority is enough - the cache engine can complete the task and process the cache memory management. The CacheItemRemovedCallback option takes place to some interesting possibilities, but in fact it rarely. However, to illustrate the method, it will provide an I Example of use: CacheItemRemovedCallback Example 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 ());} This example will use the appendlog () method (this method is not discussed here. See any logic defined in Writing Entries to Event logs to record the reasons for the data expiration in the cache. You can determine if you can use the cache or you may need to increase the memory on the server if you can use the cache or you may need to increase the memory on the server. Note that Callback is a static (SHARED in VB) method, it is recommended to use this method is that if it is not used, the instance of the class saved the callback function will remain in memory to support the callback (for static / shared method) There is no need to be). This feature has a potential use of the cache data in the background so that the user will never wait for the data to be filled, but the data is always relatively new. But in fact, this feature does not apply to the current version of the cache API because the callback is not triggered or not completed before the cached item is removed from the cache. Therefore, the user will often issue a request to access the buffer value, and then find that the cache value is empty, and has to wait for the re-filled value of the caching value. I hope to see an additional callback in the future ASP.NET version, which can be called CachedItemback, if the callback is defined, you must do execution before deleting the cache item. Cache Data Reference Mode Whenever we try to access data in the cache, you should take into account a situation, that is, the data may not be in the cache. Therefore, the following mode should be generally applicable to your access to the cache.
In this case, we assume that the cached data is a data sheet. 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 (Cachekey), Timespan.zero;} Return (DataTable) CacheItem;} About this mode, you need to pay attention to: • Some values (for example, CacheKey, CacheItem and Cache duration is defined and only defined once. Fill the cache, which includes newly inserted customers. Cache can only access it. This approach can improve performance and make sure NullReferenceExceptions, because the item exists when the item is checked, but the second time Before checking it.? This mode uses a strong type check. The "AS" operator in the C # in the C #, attempts to convert the object to the type, if it fails or the object is empty, then return null (empty).? Duration Stored in the configuration file. In the ideal case, all cache dependencies (whether file-based, or time-based, or other type 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 if you don't specify a duration for the cachekey used, let the getCacheseCondsFromConfig () method uses the default duration. Related code example is a Helper class, It will handle all of the above, but allow data to be accessed through a line or two lines of code. Please download CacheDemos.msi. Small knotacle can make the application's performance is very large Increase, so it should be considered when designing an application and performing performance testing of an application. The application general will benefit more or less from the cache, of course, some applications are more suitable for caches than other applications. The deep understanding of the cache options provided by ASP.NET is an important technique that ASP.NET developers should master.
To cache as early as possible; often cache
You should cache every layer of the application. Cache support is added to the data layer, the business logic layer, the UI, or the output layer. Memory is now very cheap now - therefore, by achieving caches throughout the application through intelligence, it can be improved.
Cache can cover a lot of negligence
The cache is a method of obtaining "sufficiently good" performance without having a large amount of time and analysis. Here again, memory is now very cheap, so if you can get the desired performance by going to the output cache for 30 seconds, not to spend a day or even a week, you can get the desired performance, you will definitely choose a cache. Solution (assuming 30 seconds of old data). Caches are one of the features that use 20% to get 80% return, so we should improve performance and should first think of cache. However, if the design is very bad, it will eventually bring bad consequences, so you must also design the application properly as possible. But if you just need to get a high enough performance, the cache is your best choice, you can re-design the application as soon as possible. Page-level output cache
As the simplest caching form, the output cache is only a copy of the HTML sent by the response request in the memory. There will then be a request to provide the output of the cache, until the cache expires, this is possible to improve significantly (depending on how much overhead is required to create the original page output - the output of the send cache is always very fast, and compare stable).