Data Cache in ASP. NET Cache

Source: Internet
Author: User

Add Cache [Key] = object or Cache. Insert

Remove Cache. Remove (key)

1. directly write the value to the Cache

The Code is as follows:
HttpContext. Current. Cache ["One"] = "1 ";
 

Use the 'absolute expires' method to process the cache. The expiration time is December 31, 9999 (this method is not recommended and the cache Key should be cleared when appropriate)


2. Insert Cache using Insert (String, Object)

The Code is as follows:
String cacheKey = "Two ";
Object cacheValue = HttpContext. Current. Cache. Get (cacheKey );

If (cacheValue = null)
{
CacheValue = WebConfigurationManager. ConnectionStrings ["ApplicationServices"]. ConnectionString;

HttpContext. Current. Cache. Insert (cacheKey, cacheValue );
}

// Display the Key and Value of the specified Cache
This. ShowMessage (cacheKey, cacheValue. ToString ());
 

3. Insert Cache using Insert (String, Object, CacheDependency, DateTime, TimeSpan)

The Code is as follows:
String cacheKey = "_ cache _ students ";

DataSet dataSet = this. Cache. Get (cacheKey) as DataSet;

If (dataSet = null)
{
DataSet = new DataSet ();

// Load the XML file and fill it with DataSet
DataSet. ReadXml (this. Server. MapPath (@ "XMLFile. xml "));

// Add the cache and set the 'absolute expiration time' to 5 minutes
This. Cache. Insert (cacheKey, dataSet, null, DateTime. Now. AddMinutes (5), System. Web. Caching. Cache. NoSlidingExpiration );
}

// Bind the DataGrid data
GrdDefault. DataSource = dataSet;
GrdDefault. DataBind ();
 

The two most important parameters of this method are absoluteExpiration and slidingExpiration.
AbsoluteExpiration DateTime type, representing the absolute expiration time
SlidingExpiration TimeSpan type, indicating the sliding expiration time
AbsoluteExpiration and slidingExpiration cannot be used simultaneously
For example, if the absoluteExpiration parameter is set, the slidingExpiration must be set to System. Web. Caching. Cache. NoSlidingExpiration.
If the slidingExpiration parameter is set, absoluteExpiration must be set to System. Web. Caching. Cache. NoAbsoluteExpiration.

4. Insert (String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority,

For more details, see http://www.bKjia. c0m/net/56762.htm

CacheItemRemovedCallback) insert Cache

Public partial class PriorityAndCallbackDemo: System. Web. UI. Page
{
# Region static field
Static bool CacheItemRemoved = false;
Static CacheItemRemovedReason Reason;
Static string CacheItemKey = "fw _ cache _ students ";
# Endregion

# Region event processing
// Page loading
Protected void Page_Load (object sender, EventArgs e)
{
// The cache item has been removed.
If (PriorityAndCallbackDemo. CacheItemRemoved)
{
LtMessage. Text = string. Format ("Key = {0} has been removed from the cache because: {1}", PriorityAndCallbackDemo. CacheItemKey, PriorityAndCallbackDemo. Reason. ToString ());
}
}

// Click "add cache" to process the event.
Protected void btnAddCache_Click (object sender, EventArgs e)
{
DataSet dataSet = this. Cache. Get (PriorityAndCallbackDemo. CacheItemKey) as DataSet;

If (dataSet = null)
{
DataSet = new DataSet ();
DataSet. ReadXml (this. Server. MapPath (@ "XMLFile. xml "));

// Use Web. config as the cache expiration dependency
CacheDependency dependency = new CacheDependency (this. Server. MapPath (@ "Web. config"), DateTime. Now );

// Add the cache and set the priority to the default level
This. cache. insert (PriorityAndCallbackDemo. cacheItemKey, dataSet, dependency, DateTime. now. addMinutes (1), System. web. caching. cache. noSlidingExpiration, CacheItemPriority. default, new CacheItemRemovedCallback (this. cacheItemRemovedHandler ));
}

// Bind the GridView data
GrdDefault. DataSource = dataSet;
GrdDefault. DataBind ();
}

// Click the 'Remove cache' button to process the event.
Protected void btnRemoveCache_Click (object sender, EventArgs e)
{
If (this. Cache [PriorityAndCallbackDemo. CacheItemKey]! = Null)
{
This. Cache. Remove (PriorityAndCallbackDemo. CacheItemKey );
}
}
# Endregion

# Region private Method
// Handle cache item removal events
Private void CacheItemRemovedHandler (string key, object value, CacheItemRemovedReason relason)
{
PriorityAndCallbackDemo. CacheItemRemoved = true;
PriorityAndCallbackDemo. Reason = relason;
}
# Endregion
}
 

Two important parameters of this method are CacheItemPriority and CacheItemRemovedCallback.
CacheItemPriority indicates the priority of cache items. When the server memory is insufficient, items with a higher priority are not easily removed.
CacheItemRemovedCallback this parameter is of the delegate type. It is called when a cache item is removed. The Reason parameter is used to indicate the Reason why the cache item is removed.

[How do I use it]

First, understand the cache policy. You can call an expiration policy or an absolute expiration policy. Note: The two cannot be used at the same time.
 

To use the callable expiration policy, you need to set the absoluteExpiration = DateTime. MaxValue, TimeSpan. FromMinutes (10) item to be removed only if it is not used within 10 minutes.

The Code is as follows:
Cache. Insert ("data", "123", null, DateTime. MaxValue, TimeSpan. FromMinutes (10 ));
 

Absolute Strategy, such as weather report, to save information for 60 minutes

The Code is as follows:
Cache. Insert ("data", "123", null, DateTime. Now. AddMinutes (60), TimeSpan. Zero );
 

Cache dependency.

That is, the invalidation of a cache depends on another object. The object here can refer to another cache, or a file, or ....


Class: CacheDependency namespace System. Web. Caching. CacheDependency depends on other cache Projects
 

The Code is as follows:
System. Web. Caching. CacheDependency cacheDependency = new System. Web. Caching. CacheDependency (null, new string [] {"time "});
Cache. Insert ("number", ++ num, cacheDependency );
 
Dependent on files or folders
 
System. Web. Caching. CacheDependency cacheDependency = new System. Web. Caching. CacheDependency ("test. xml ");
Automatically removed from the cache when the test. xml file is deleted or updated
 
System. Web. Caching. CacheDependency cacheDependency = new System. Web. Caching. CacheDependency (null, new string [] {"time "});
Cache. Insert ("test", "123", cacheDependency );

 
Remove project callback
Cache. Insert ("test", "123", null, DateTime. Now. AddSeconds (10), TimeSpan. Zero, new CacheItemUpdateCallback (Test ));
 
 
Private void Test (string key, CacheItemUpdateReason reason, out object expensiveObject, out CacheDependency dependency, out DateTime absoluteExpiration, out TimeSpan slidingExpiration)
{
 
}
 
 

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.