How. Net uses cache framework to add cache to program

Time:2021-6-6

Net 4.0 adds a new system.runtime.caching namespace, which provides a series of extensible cache framework. This paper briefly introduces how to use it to add cache to programs.

A cache framework mainly includes three parts: objectcache, cacheitempolicy and changemonitor.

ObjectCacheRepresents a cache pool, which provides interfaces for adding, obtaining, and updating cache objects. It is the main body of the cache framework. It is an abstract class, and the system gives a common implementation — memorycache.
CacheItemPolicyIndicates the cache expiration policy, such as expiration after a certain time. It is also often used with changemonitor to implement more complex policies.
ChangeMonitorIt is mainly responsible for maintaining the state of the cachepool object and judging whether the object needs to be updated. It is also an abstract class. The system also provides several common implementations: cacheentrychangemonitor, filechangemonitor, hostfilechangemonitor and sqlchangemonitor.

1. First, create a new general control program and add a class. The code is as follows

#region 
class MyCachePool
  {
    ObjectCache cache = MemoryCache.Default;
    const string CacheKey = "TestCacheKey";

  //If you define the string type constant cachekey and assign the initial value to testcachekey, you cannot change the value of cachekey 
  //For example, execute cachekey = 2; The value of a is always testcachekey in the whole program


    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, when the object is not accessed within 3 seconds, it will expire. If the object is always accessed, it does not expire.

        AbsoluteExpiration = DateTime.Now.AddSeconds(3)
        //In the second expiration policy, cache content will expire after more than 3 seconds.


        content = Guid.NewGuid().ToString();
        cache.Set(CacheKey, content, policy);
      }
      else
      {
        Console.WriteLine("Get cached item");
      }

      return content;
    }

#endregion

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 cache to save for 3 seconds: the same value is obtained within 3 seconds. After 3 seconds, the data is expired, and the cache is updated to get a new value.

Expiration policy:

From the previous example, we can see that when a cache object is added to the cachepool, a cacheitempolicy object is added at the same time, which controls the cache object’s expiration. For example, in the previous example, we set the timeout policy as follows: absolute expiration = datetime. Now. Addseconds (3). It represents an absolute time expiration. After more than 3 seconds, the cache content will expire.

In addition, we also have a more common overdue policy: according to the visit frequency to determine the overdue. For example, if we set the following policy: slipingexpiration = timespan. Fromseconds (3). It means that an object will expire if it is not accessed within 3 seconds. In contrast, if the object is accessed all the time, it does not expire. These two strategies cannot be used at the same time. So I’ve commented in the above code.

Cacheitempolicy can also set up updatecallback and removedcallback, which is very convenient for us to log or perform some processing operations.

ChangeMonitor

Although the expiration policies listed above are very common, they can meet our needs most of the time. But sometimes, expiration policy can’t be judged simply by time. For example, the content of my cache is read from a text file. At this time, the condition of expiration is whether the content of the file has changed: when the file has not changed, the cache content is returned directly. When asked about the change, the cache content is overdue and the file needs to be read again. At this time, we need to use changemonitor to realize more advanced overdue judgment.

Since the system has provided a change monitor for file changes – hostfilechange monitor, you don’t need to implement it yourself. You can use it directly.

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 is used to solve garbled problems

     //StreamReader sr = new StreamReader(file, Encoding.Default);
     //content = sr.ReadToEnd();
     //sr.Close();
    //The second reading method

    cache.Set(cacheKey, content, policy);


    }
    else
    {
      Console.WriteLine("Get cached item");
    }

    return content;
  }

This example is relatively simple. For those policies without custom, we need to implement our own changemonitor. Next time I have time to write a more in-depth introduction.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.