Example introduction to. NET using the cache framework

Source: Internet
Author: User
A new System.Runtime.Caching namespace has been added to. NET 4.0, which provides a series of extensible cache frameworks, and this article simply describes how to use it to add a cache to a program.

A cache framework consists of three main parts: ObjectCache, CacheItemPolicy, ChangeMonitor.

ObjectCache represents a cachepool that provides an interface for adding, retrieving, and updating the cache object, which is the body of the cache framework. It is an abstract class, and the system gives a common implementation--memorycache.

CacheItemPolicy indicates a cache expiration policy, such as expiration after a certain amount of time has been saved. It is also often used with changemonitor to achieve more complex strategies.

ChangeMonitor is mainly responsible for the state maintenance of Cachepool objects, and determines whether objects need to be updated. It is also an abstract class, and the system provides several common implementations: Cacheentrychangemonitor, Filechangemonitor, Hostfilechangemonitor, Sqlchangemonitor.

ObjectCache represents a cachepool that provides an interface for adding, retrieving, and updating the cache object, which is the body of the cache framework. It is an abstract class, and the system gives a common implementation--memorycache.

CacheItemPolicy indicates a cache expiration policy, such as expiration after a certain amount of time has been saved. It is also often used with changemonitor to achieve more complex strategies.
ChangeMonitor is mainly responsible for the state maintenance of Cachepool objects, and determines whether objects need to be updated. It is also an abstract class, and the system provides several common implementations: Cacheentrychangemonitor, Filechangemonitor, Hostfilechangemonitor, Sqlchangemonitor.

1, first create a general control program, add a class, where the code is as follows

#region class Mycachepool  {    ObjectCache cache = Memorycache.default;    Const string CacheKey = "Testcachekey"; Define the string type constant CacheKey and assign the initial value to Testcachekey, then can not change the values of CacheKey//such as the execution cachekey= "2"; will run the error throughout the program A's value is always testcachekey public    string GetValue ()    {      var content = Cache[cachekey] As String;      if (content = = null)      {        Console.WriteLine ("Get New Item"); slidingexpiration = Timespan.fromseconds (3)        //The first expiration policy expires when the object is not accessed within 3 seconds. If the object is always accessed, it will not expire.        absoluteexpiration = DateTime.Now.AddSeconds (3)        //second expiration policy, after 3 seconds, the cache content expires.        content = Guid.NewGuid (). ToString ();        Cache. Set (CacheKey, content, policy);      }      else      {        Console.WriteLine ("Get cached Item");      }      return content;    } #endregion

Again at the main program entrance

static void Main (string[] args) {Mycachepool pool = new Mycachepool ();  MyCachePool1 pool1 = new MyCachePool1 ();    while (true) {thread.sleep (1000); var value = pool.    GetValue ();    var value = Pool1.mygetvalue ();    Console.WriteLine (value); Console.WriteLine (); }}

This example creates a save for 3 seconds cache: Three seconds to get the same value, more than 3 seconds after the data expires, update the cache, get to the new value.

Expiration policy:

As we can see from the previous example, when a cache object is added to Cachepool, a CacheItemPolicy object is added, which controls the expiration of the cache object. For example, in the previous example, we set the timeout policy in the following way: Absoluteexpiration = DateTime.Now.AddSeconds (3). It represents an absolute time expiration, and after more than 3 seconds, the cache content expires.

In addition, we also have a more common extended strategy: according to the frequency of access to determine the extended. For example, if we set the following extended policy: slidingexpiration = Timespan.fromseconds (3). It indicates that the object expires when it is not accessed within 3 seconds. In contrast, if the object is always accessed, it will not expire. These two policies cannot be used at the same time. So I've commented on the code above.

CacheItemPolicy can also be developed updatecallback and RemovedCallback, convenient for us to log or perform some processing operations, very convenient.

ChangeMonitor

Although the previous expiration policy is a very common strategy, it can satisfy most of our needs. But sometimes, expiration strategies cannot be judged simply by time. For example, the content of my cache is read from a text file, and the condition of expiration is whether the contents of the file change: When the file is not changed, the cache content is returned directly, and when asked about the change, the cache content is extended and the file needs to be re-read. At this time, we need to use ChangeMonitor to achieve more advanced extended judgment.

Because the system has already provided the file change Changemonitor--hostfilechangemonitor, here does not have to implement, the direct use can.

 public string GetValue () {var content = Cache[cachekey] As String;     if (content = = null) {Console.WriteLine ("Second Expiration Method");     var file = "C:\\users\\administrator\\desktop\\test.txt";     CacheItemPolicy policy = new CacheItemPolicy (); Policy.     Changemonitors.add (New Hostfilechangemonitor (new list<string> {file})); Content = File.readalltext (File, Encoding.default);     Encoding.default for solving garbled problems//streamreader sr = new StreamReader (file, Encoding.default); Content = Sr.     ReadToEnd (); Sr.    Close (); The second way to read the cache.    Set (CacheKey, content, policy);    } else {Console.WriteLine ("Get cached Item");  } return content; }
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.