1) Cache ASP.NET Page 1 Operate the HTTPCACHEPOLICY class programmatically. HttpCachePolicy.SetExpires HttpCachePolicy.SetCacheability | NoCache | Private | Public | Server | ServerAndNoCache | ServerAndPrivate 2 <% @ OutputCache Duration = "60" VaryByParam = "None"%> Duration and VaryByParam property is required.
2) Capache some parts of the ASP.NET page cache, do not always request the server
The control header, one version of the control will store 120 seconds in the output cache. <% @ Outputcache duration = "120" VarybyParam = "none"%>
Or use the code hidden development method to develop user controls, then include the following properties in the metadata of the class declaration, the control version will store 120 seconds in the output cache. [Partialcaching (120)]
The above two methods will only cache user controls. You can also use it, cache controls in the cached page or control.
You can declare the ID attribute in the user control tag that has been specified for the output cache, so that the instance of the user control can be programmed. However, in order to make the code work properly, you must explicitly verify that the user control exists in the output cache. !! Possible error: If you write a code to operate a user control containing the @ OutputCache directive, an error will occur.
In addition, if the page output cache is set to 100 seconds, and the user control output cache is set to 50 seconds, the entire page will store 100 seconds in the output cache, while the user control is not related to the time setting of the user control. However, if the page output cache storage duration is shorter than the user control storage duration, the cache user output control will always be used until its storage time expires, even if the rest of the page is regenerated for a request. For example, if the page output cache is set to 50 seconds, and the user control output cache is set to 100 seconds, the rest of the page is two times, and the user control expires once.
3) Cache application data allows you to store a large number of server resources to create objects stored in memory. It is implemented by the Cache class, an example is dedicated to each application, and its survival depends on the survival of the application. After restarting the application, you will recreate the Cache object.
See: ms-help: //ms.vscc.2003/ms.msdnqtr.2003feb.2052/cpguide/html/cpconcacheapis.htm~~~~~~~~~~~~ ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~ (General) Allows you to need a large number of server resources to create objects stored in memory. It is implemented by the Cache class, an example is dedicated to each application, and its survival depends on the survival of the application. After restarting the application, you will recreate the Cache object. ASP.NET provides you with a powerful, easy-to-use caching mechanism that allows you to need a large number of server resources to create objects stored in memory. It is implemented by the Cache class, an example is dedicated to each application, and its survival depends on the survival of the application. After restarting the application, you will recreate the Cache object.
The design Cache class is for easy use. By using the key to the pair, you can place the item in cache and retrieve them later. For examples of how to do this, see Adding an item to the cache and retrieve the cache item.
The Cache class provides you with a simple interface from defining cache settings, which also provides a powerful feature allows you to customize how to cache items and how long it is caching. For example, when lacking system memory, the cache automatically removes rarely used or unimportant items to allow memory to handle a large number of requests. This technology is called cleaning. This is a way to ensure that non-current data does not use valuable server resources.
When cleaning, you can indicate that cache gives some items than other items. To indicate that a particular item has high or lower importance than other items, specify a cacheItemPriority enumeration value when adding items with a cache.add method or cache.insert method.
When you use the Add method or the Insert method Add your item to cache, you can also create the expiration policy. You can use the AbsoluteExPiration parameter definition item, this parameter is a DateTime type, which allows you to specify the exact expiration time of the item. You can also use the SLIDINGEXPIRATION parameter, which is the TimeSpan type. It allows you to specify the runtime before the expiration of the access item. Once this expires, it will be removed from the cache. Attempting to retrieve its value will return NULL unless the item is re-added to Cache.
For easy-to-entries stored in Cache (such as items that often perform data refresh or items only in a period of time), set a expiration policy, as long as the data of these items remains up to date, Keep in Cache. For example, if you are writing an application, the application will track the score of the sports competition by getting data from a frequently updated Web site, then these scores can be cached only if the score of the game is not changed from a web site. In this case, you can set the expiration policy based on the frequency of the Web site update score. You can write code to determine if you are the latest score in Cache. If the score is not the latest, the code can update the score from the source web site.
Finally, ASP.NET allows you to define the validity of the cache items based on external files, directories, or another cache item. These are called file-dependent and key dependencies. If relying on item changes, the cache item fails and removed from the Cache. You can use this technology to remove these items from the Cache when you change the data source changes. For example, if you write an application that handles financial data in an XML file, you can rendering it in the graph, you can insert the data from the file into the Cache and keep a dependencies on the XML file. When the file is updated, the item is removed from the cache, and your application re-reads the file and inserts a new version of the item. Note that cache does not have information about the contents of the items it contain. It only retains references to these objects. It also provides methods that track their dependencies and setting expiration strategies.
(1) Add item to the cache
You can use three different technologies to add items to the Cache object. According to the application requirements, your selection can be easily complicated. If you want to use Cache's cleanup, expiration time, and dependencies, you must use the cache.insert method or cache.add method. Note that the add and insert methods have the same signature, but there is a subtle difference between them. First, call the Add method to return to the object indicating the cache item, and call the INSERT method is not. Second, if you call these methods and add an item stored in Cache to Cache, then their behavior is different. The INSERT method replaces this, and the ADD method fails. Adding items to the cache by specifying their keys and values, you can add it to the cache as the item added to the dictionary. The following code adds the current value attribute of the text box to the Cache. [Visual Basic] cache ("txt1") = txtname.value [c #] cache ["txt1"] = txtName.Value; Remove the INSERT method to the cache by using the INSERT method, allow you to define the version being used The value of the parameters. For example, if you want to add a key and value of an item, use the following code. [Visual Basic] cache.insert ("MyData1", Connectionstring) [CACHE.INSERT ("MyData1", Connectionstring); Use the add method to add an item to the cache add method with the INSERT method, but it returns Indicates the object you add. [Visual Basic] cache.add ("MyData1", Connectionstring) [C #] Cache.Add ("MyData1", Connectionstring); Both methods enable you to control the conditions for retention in Cache to a large extent. Both methods support the entries that make the cache depend on external files or directories, other keys in Cache or arbitrary array. Add an item with dependencies to cache to create an instance of the Cachedependency class, which track changes to your definition dependencies. If any of these dependencies have changed (including deleted or moving), the item associated with the dependency is removed from the Cache. Add items with dependencies to the cache You can add items with dependencies to Cache using the DependenCIES parameters in the Add or INSERT method. The following example demonstrates the item with the INSERT method to add an item (on the XML file) to the Cache. [C #] Cache.Insert ( "MyData1", connectionString, new CacheDependency (Server.MapPath (// myServer / myConfig.xml))); [Visual Basic] Cache.Insert ( "MyData1", connectionString, new CacheDependency (Server. Mappath (// myServer / myconfig.xml)) Add Items The items with the GF Policy You can use the AbsoluteExpiration Parameter parameter and the SLIDINGEXPIRATION parameter to add items with the expiration policy to Cache. You can define absolute expiration time or flexible expiration time, but you can't define both. When one of the above parameters is used to define the expiration policy, the other parameter must be set to zero.
The Cache class defines two fields that automatically execute the operation: NoabSoluteExpiration and NoslidingExpiration. When defining an absolute or flexible expiration time, as long as the appropriate parameter is set to its corresponding field value. The following example uses the INSERT method to add an item with a two-minute absolute expiration time to Cache. [C #] cache.insert ("MyData1", Connectionstring, Null, DateTime.now.addminutes (2), NoslidingExpiration); [Visual Basic] Cache.Insert ("MyData1", Connectionstring, Null, DateTime.now.addminutes (2 ), NoslidingExpiration) The following code uses the INSERT method to add an item with a 30-second flexible expiration time to Cache. [C #] Cache.Insert ( "MyData1", connectionString, null, NoAbsoluteExpiration, TimeSpan.FromSeconds (30)); [Visual Basic] Cache.Insert ( "MyData1", connectionString, null, NoAbsoluteExpiration, TimeSpan.FromSeconds (30)) Note When setting an absolute expiration time, use the DateTime structure. Use the Timespan structure when setting the flexible expiration time. Also, if you create the elastic expiration time of less than zero or more, the ArgumentOutofrangeException class will be triggered. You can also use the Add or INSERT method to define the relative importance of the cache item in the CacheItemPriority enumeration. These relative priorities will help it when the web server cleans up to release memory. The web server will remove items with lower priority from Cache before removing items with higher priority. Add items with priority settings to the cache You can add items with priority settings to Cache by using the Priority parameter on the add or insert method. The following example uses the Add method to add Priority to the high to Cache. [C #] Cache.Add ( "MyData1", connectionString, null, NoAbsoluteExpiration, TimeSpan.FromSeconds (30), CacheItemPriority.High, null); [Visual Basic] Cache.Add ( "MyData1", connectionString, null, NoAbsoluteExpiration, TimeSpan .Fromseconds (30), cacheitempriority.high, null (2) Notify the application when deleting items from the cache
ASP.NET provides CacheItemRemovedCallback commission. It defines the signature used when writing an event handler. When the item is removed from the cache, the event handler will respond. ASP.NET also provides CacheItemRemoveDreason enumeration, you can use this enumeration to delete the reason why the event is deleted.
Notify the application when you delete an item from the cache
Create a local variable that initiates the event of CacheItemRemoveDCallback entrusted. For example, the following code creates a type of onRemoveDCallback for CacheItemRemovedCallback. Private static cacheItemRemovedCallback onremove = null;
Note that this variable must be used for this type in order to use the onRemoveCallback parameters of cache.add or cache.insert methods in the fourth step. Create an event handler that responds when the item is removed from the cache. For example, the following code sets the static Boolean itemRemoved to TRUE, set the static CacheItemRemoveDreason REASON to transfer the value passed when the item is removed from the cache. Note that members using CacheItemRemoveDreason enumeration to create a condition code for this step for this step is a way you can choose. [C #] CacheItemRemovedReason reason; public void RemovedCallback (string key, object value, CacheItemRemovedReason callbackreason) {reason = r;} [Visual Basic] Dim reason As CacheItemRemovedReasonPublic Sub RemovedCallback (key As String, value As Object, reason As CacheItemRemovedReason) reason = Rend sub
Note that the event handler must use the same signature as CacheItemRemovedCallback. This code assumes that you have created two static variables: types of ItemRemoved and types of cacheItemRemovedreason's REASON. Create an instance of the CacheItemRemoveDCallback commission that calls the event handler. The following code calls the method created in the second step. OnRemove = New CacheItemRemovedCallback (this.RemovedCallback);
Add items to Cache using cache.add methods or cache.insert methods. You must specify the local variable created in the first step in the OnRemoveCallback parameter. The following code uses the INSERT method to add a cache, the key of the key is "MyData1", the value is Source. It defines the onRemove variable in the OnRemoveCallback parameter. Cache.insert ("MyData1", Source, Null, DateTime.now.addminutes (2), NoslidingExpiration, CacheItemPriority.high, OnRemove;
When the item added in the fourth step is removed from the Cache due to any reason, the REMOVALLBACK method will be called, and the code it can be accessed to present the new content to the request client or notify the application in an appropriate manner you choose. program.
(3) Retrieve the value of the cache item
The following code creates a Source DataView object and attempts to retrieve the cache data assigned the key MyData1 and assign the data to the Source. Then, confirm that the data is still stored in the cache and assigns the Source as the DataSource property of the DataGrid Web Server Control MyDataGrid. Finally, the data is bound to myDataGrid. [C #] DataView Source; Source = (DataView) Cache ["MyData1"];
IF (source! = null) {myDataGrid.datasource = source; mydatagrid.database ();
Check if an example exists in the example below to modify the code during the previous process to check if the cache is present. If it is not in the cache, the sample recreate it and add it to the cache. [C #] DataView Source = (DataView) Cache [ "MyData1"]; if (Source == null) {SqlConnection myConnection = new SqlConnection ( "server = localhost; Integrated Security = SSPI; database = pubs"); SqlDataAdapter myCommand = new SqldataAdapter ("Select * from authors", myconnection; dataset ds = new dataset (); MyCommand.Fill (DS, "Authors");
Source = New DataView (DS.Tables ["Authors"]); cache ["mydata1"] = source;} mydatagrid.datasource = source; mydatagrid.databind ();