Use of cache in C #

Source: Internet
Author: User
Tags filegroup server hosting

Public methods
Add adds the specified item to the Cache object, which has dependencies, expiration and priority policies, and a delegate that can be used to notify the application when an insert item is removed from the cache.
Equals (inherited from Object) is overloaded. Determines whether two instances of Object are equal.
Get retrieves the specified item from the Cache object.
GetEnumerator retrieves a dictionary enumerator that is used to iterate through the key settings and their values contained in the cache.
GetHashCode (inherited from Object) serves as a hash function for a particular type and is suitable for use in hashing algorithms and data structures such as a hash table.
GetType (inherits from Object) gets the Type of the current instance.
Insert is overloaded. Inserts an item into the Cache object. Use a version of this method to overwrite an existing Cache entry with the same key parameter.
Remove removes the specified item from the application's Cache object.
ToString (inherited from Object) returns a String that represents the current object.


public Object Add (
String key,
Object value,
CacheDependency dependencies,
DateTime absoluteexpiration,
TimeSpan slidingexpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
);

Parameters
Key
The cache key used to reference the item.
Value
The item to add to the cache.
Dependencies
The item's file dependency or cache key dependency. When any dependency changes, the object is not valid and is removed from the cache. If there are no dependencies, this parameter contains a null reference (Nothing in Visual Basic).
Absoluteexpiration
The time that the added object will expire and be removed from the cache.
SlidingExpiration
The time interval between when the object was last accessed and when the object expires. If the value is equivalent to 20 minutes, the object expires and is removed from the cache after the last 20 minutes of access.
Priority
The relative cost of the object, represented by the CacheItemPriority enumeration. The cache uses this value when exiting an object, and objects with lower costs are removed from the cache before they have higher cost objects.
onRemoveCallback
The delegate, if provided, that is invoked when an object is removed from the cache. When you delete an application's object from the cache, you can use it to notify the application.
Example
public void Additemtocache (Object sender, EventArgs e) {
ItemRemoved = false;

OnRemove = new CacheItemRemovedCallback (this. RemovedCallback);

if (cache["Key1"] = = null)
Cache.Add ("Key1", "Value 1", NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero, Cacheitempriority.high, onremove);
}

Adding data to the cache

1. Add an item to the cache by specifying its key and value
cache["txt"] = "a";

2. Add items to the cache by using the Insert (overloaded Insert method) method

Cache.Insert ("TXT", "a");

The following code shows how to set a relative expiration policy. It inserts an item that expires 10 minutes after the last access. Note the use of DateTime.MaxValue, which indicates that this item does not have an absolute expiration policy.

DateTime Absoluteexpiration=datetime.maxvalue;
TimeSpan slidingexpiration=timespan.fromminutes (10);
Cache.Insert ("TXT", "a", NULL,
Absoluteexpiration,slidingexpiration,
System.web.caching.cacheitempriority.high,null);

3. Add an item to the cache using the Add method
The Add method has the same signature as the Insert method, but it returns the object that represents the item you added

DateTime Absoluteexpiration=datetime.maxvalue;
TimeSpan slidingexpiration=timespan.fromminutes (10);
Object ojb= (String) cache.add ("TXT", "a", NULL,
Absoluteexpiration, SlidingExpiration,
System.web.caching.cacheitempriority.high,null);
String str= (String) OJB;
Response.Write (str);

The results show "a"

The Add method uses no Insert method flexibility, using the Add method must provide 7 parameters, Insert method overload 4 times, we can choose the appropriate overloaded method as needed


Getting data from the cache

Mode 1:
String str= (String) cache.get ("txt");
Response.Write (str);

Mode 2:
String str1= (String) cache["Txt1"];
Response.Write (STR1);

View all data in the cache

System.Text.StringBuilder sb=new System.Text.StringBuilder ("", 100);
foreach (DictionaryEntry Caches in Cache)
{
Sb. Append ("key="). Append (Caches.Key.ToString ()). Append ("
") ;
Sb. Append ("value="). Append (Caches.Value.ToString ()). Append ("
");
}
Response.Write (sb.) ToString ());

View the number of items in the cache

int count=cache.count;
Response.Write (Count.tostring ());


To remove data from the cache

Cache.remove ("txt");

Object that causes the cache to have a file dependency or key dependency

We set up 1 buttons on a page to see if the cache exists
When the form starts we create the cache, name = "Txt2", Value = DataSet ds
The cache is associated with Myfile.xml and is automatically deleted when the Myfile.xml file changes Txt2cache

private void Page_Load (object sender, System.EventArgs e)
{
if (! IsPostBack)
{
String Filepath=mappath ("Myfile.xml");
SqlConnection con=new SqlConnection ("uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter ("select * from authors", con);
DataSet ds=new DataSet ();
Da. Fill (DS);
System.Web.Caching.CacheDependency cachedependencyxmlfile=new System.Web.Caching.CacheDependency (FilePath);
Cache.Insert ("Txt2", DS, Cachedependencyxmlfile);
}
}


To monitor changes in the Pubs database Authors table
We can create a trigger in the Pubs database Authors table
Once the authors table has increased, deleted, modified data, the trigger will automatically modify the file Myfile.xml
Once the Myfile.xml file changes, Txt2cache is automatically deleted by the system.

CREATE TRIGGER tr_authors
On authors
For INSERT, UPDATE, delete
As
declare @cmd nvarchar (4000)
Select @cmd = ' bcp ' select convert (nvarchar (+), Getdate (), "Queryout d:/cache/webcache/myfile.xml-c-sglc2403-usa-p ‘
EXEC master. xp_cmdshell @cmd
GO


private void Querybutton_click (object sender, System.EventArgs e)
{
if (cache["Txt2"]!=null)
{
Response.Write ("exists");
}
Else
{
Response.Write ("not exists");
}
}

First we click the button to show cache["Txt2"] exists
Now we go to the table authors arbitrarily modify a data, then click the button, the display cache["TXT2"] does not exist pull


Above we are the cache is associated with a file, we can also associate the cache and the filegroup, establish a dependency
Here we associate the cache with 2 files (myfile.xml,myfile1.xml), and once any of the files in the filegroup changes, the cache will delete the "TXT2" item's data from the cache

String[] filepath=new string[]{mappath ("Myfile.xml"), MapPath ("Myfile1.xml")};
System.Web.Caching.CacheDependency cachedependencyxmlfile=new System.Web.Caching.CacheDependency (filep ATH);
String cachevaule= "a";
Cache.Insert ("Txt2", Cachevaule, Cachedependencyxmlfile);


The cache dependency can be a file, or it can be a key for another object
The following code shows that the cache cache["Txt2" depends on both the file Myfile.xml and the cache["TXT" in the cache, and as long as the 2 changes arbitrarily, the cache cache["Txt2" will clear

cache["txt"] = "B";
String[] filepath=new string[]{MapPath ("Myfile.xml")};
String[] dependencykey=new string[]{"txt"};
SqlConnection con=new SqlConnection ("uid=sa;database=pubs;");
SqlDataAdapter da =new SqlDataAdapter ("select * from authors", con);
DataSet ds=new DataSet ();
Da. Fill (DS);
System.Web.Caching.CacheDependency cachedependencyxmlfile=
New System.Web.Caching.CacheDependency (Filepath,dependencykey);
Cache.Insert ("Txt2", DS, Cachedependencyxmlfile);


Cache Absolute Expiration

Cache cache["TXT3"] automatically expires after 1 hours
DateTime absoluteexpiration =datetime.now.addhours (1);
Cache.Insert ("Txt3", "AA", null,absoluteexpiration,system.web.caching.cache.noslidingexpiration);

Cache relative (sliding) expiration

Note: If you create an elastic expiration time of less than 0 or greater than one year, an exception is thrown
Cache cache["TXT4") automatically expires 1 hours after the last access
TimeSpan slidingexpiration=timespan.fromhours (1);
Cache.Insert ("Txt4", "4", null,system.web.caching.cache.noabsoluteexpiration,slidingexpiration);


Priority level of cache entries

When a WEB server hosting an ASP. NET application is missing memory, the Cache selectively clears the item to free up system memory. When you add an item to the cache, you can assign it a relative priority that is compared to other items stored in the cache. When the server processes a large number of requests, items assigned higher priority values are less likely to be removed from the cache, and items with lower priority values are more likely to be deleted.
Represented by the CacheItemPriority enumeration, which defaults to Normal.

Cache cache["TXT5"] priority is set to the highest level, and the cache entry is most unlikely to be deleted when the server frees up system memory.
Cache.Insert ("Txt5", "5", NULL,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.web.caching.cacheitempriority.high,null);

Notifies the application of callback methods when the item is cached

ASP. NET provides CacheItemRemovedCallback delegates. It defines the signature that is used when the event handler is written, and the event handler responds when an item is removed from the cache.


static System.Web.Caching.CacheItemRemovedReason reason;
System.Web.Caching.CacheItemRemovedCallback onremove = null;

public void RemovedCallback (String K, Object V, System.Web.Caching.CacheItemRemovedReason R)
{
ItemRemoved = true;
Reason = R;
}

OnRemove = new System.Web.Caching.CacheItemRemovedCallback (this. RemovedCallback);
Cache.Insert ("txt", Ds,null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.web.caching.cacheitempriority.default,onremove);

The RemovedCallback method is called when it is removed from the cache for any reason

Source: http://blog.csdn.net/thecityofsky/article/details/4770231

Use of cache in C #

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.