An example of how .net uses the Cache framework
.NET 4.0中新增了一个System.Runtime.Caching的名字空间,它提供了一系列可扩展的Cache框架,本文就简单的介绍一下如何使用它给程序添加Cache。
一个Cache框架主要包括三个部分:ObjectCache、CacheItemPolicy、ChangeMonitor。
ObjectCache表示一个CachePool,它提供了Cache对象的添加、获取、更新等接口,是Cache框架的主体。它是一个抽象类,并且系统给了一个常用的实现——MemoryCache。
CacheItemPolicy则表示Cache过期策略,例如保存一定时间后过期。它也经常和ChangeMonitor一起使用,以实现更复杂的策略。
ChangeMonitor则主要负责CachePool对象的状态维护,判断对象是否需要更新。它也是一个抽象类,系统也提供了几个常见的实现:CacheEntryChangeMonitor、FileChangeMonitor、HostFileChangeMonitor、SqlChangeMonitor。
ObjectCache表示一个CachePool,它提供了Cache对象的添加、获取、更新等接口,是Cache框架的主体。它是一个抽象类,并且系统给了一个常用的实现——MemoryCache。
CacheItemPolicy则表示Cache过期策略,例如保存一定时间后过期。它也经常和ChangeMonitor一起使用,以实现更复杂的策略。
ChangeMonitor则主要负责CachePool对象的状态维护,判断对象是否需要更新。它也是一个抽象类,系统也提供了几个常见的实现:CacheEntryChangeMonitor、FileChangeMonitor、HostFileChangeMonitor、SqlChangeMonitor。
1、首先新建一个一般控制程序,添加一个类,其中代码如下
#region class MyCachePool { ObjectCache cache = MemoryCache.Default; const string CacheKey = "TestCacheKey"; //定义字符串类型常量CacheKey并赋初值为TestCacheKey,那么不能再改变CacheKey的值 //如执行CacheKey="2"; 就会运行错误在整个程序中 a的值始终为TestCacheKey public string GetValue() { var content = cache[CacheKey] as string; if(content == null) { Console.WriteLine("Get New Item"); //SlidingExpiration = TimeSpan.FromSeconds(3) //第一种过期策略,当对象3秒钟内没有得到访问时,就会过期。如果对象一直被访问,则不会过期。 AbsoluteExpiration = DateTime.Now.AddSeconds(3) //第二种过期策略,当超过3秒钟后,Cache内容就会过期。 content = Guid.NewGuid().ToString(); cache.Set(CacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; } #endregion
再在主程序入口
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(); } }
这个例子创建了一个保存3秒钟Cache:三秒钟内获取到的是同一个值,超过3秒钟后,数据过期,更新Cache,获取到新的值。
过期策略:
从前面的例子中我们可以看到,将一个Cache对象加入CachePool中的时候,同时加入了一个CacheItemPolicy对象,它实现着对Cache对象超期的控制。例如前面的例子中,我们设置超时策略的方式是:AbsoluteExpiration = DateTime.Now.AddSeconds(3)。它表示的是一个绝对时间过期,当超过3秒钟后,Cache内容就会过期。
除此之外,我们还有一种比较常见的超期策略:按访问频度决定超期。例如,如果我们设置如下超期策略:SlidingExpiration = TimeSpan.FromSeconds(3)。它表示当对象3秒钟内没有得到访问时,就会过期。相对的,如果对象一直被访问,则不会过期。这两个策略并不能同时使用。所以说上面代码中我已注释。
CacheItemPolicy也可以制定UpdateCallback和RemovedCallback,方便我们记日志或执行一些处理操作,非常方便。
ChangeMonitor
虽然前面列举的过期策略是非常常用的策略,能满足我们大多数时候的需求。但是有的时候,过期策略并不能简单的按照时间来判断。例如,我Cache的内容是从一个文本文件中读取的,此时过期的条件则是文件内容是否发生变化:当文件没有发生变更时,直接返回Cache内容,当问及发生变更时,Cache内容超期,需要重新读取文件。这个时候就需要用到ChangeMonitor来实现更为高级的超期判断了。
由于系统已经提供了文件变化的ChangeMonitor——HostFileChangeMonitor,这里就不用自己实现了,直接使用即可。
public string GetValue() { var content = cache[CacheKey] as string; if(content == null) { Console.WriteLine("第二种过期方式"); 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用于解决乱码问题 //StreamReader sr = new StreamReader(file, Encoding.Default); //content = sr.ReadToEnd(); //sr.Close(); //第二种读取方式 cache.Set(cacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; }
The above is the detailed content of An example of how .net uses the Cache framework. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Support Vector Machine (SVM) in Python is a powerful supervised learning algorithm that can be used to solve classification and regression problems. SVM performs well when dealing with high-dimensional data and non-linear problems, and is widely used in data mining, image classification, text classification, bioinformatics and other fields. In this article, we will introduce an example of using SVM for classification in Python. We will use the SVM model from the scikit-learn library

The thing is actually like this. At that time, my leader gave me a perf hardware performance monitoring task. During the process of using perf, I entered the command perf list and I saw the following information: My task is to enable these cache events to be counted normally. But the point is, I have no idea what these misses and loads mean.

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

As the new generation of front-end frameworks continues to emerge, VUE3 is loved as a fast, flexible, and easy-to-use front-end framework. Next, let's learn the basics of VUE3 and make a simple video player. 1. Install VUE3 First, we need to install VUE3 locally. Open the command line tool and execute the following command: npminstallvue@next Then, create a new HTML file and introduce VUE3: <!doctypehtml>

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

Characteristics of cache: A one- or two-level high-speed, small-capacity memory set between the CPU and the main memory. The information is naturally lost when the computer is powered off. Characteristics of ROM: it can only read data from the memory, but cannot write information into it. The data will still exist after the computer is powered off. Characteristics of ram: it can read data from the memory and write information to the memory; it is used to store commands, programs and data required to run the program; information is naturally lost when the computer is powered off.

Cache is called cache memory. It is a high-speed small-capacity memory between the central processing unit and the main memory. It is generally composed of high-speed SRAM. This kind of local memory is oriented to the CPU. It is introduced to reduce or eliminate the gap between the CPU and the memory. The impact of the speed difference between them on system performance. Cache capacity is small but fast, memory speed is low but capacity is large. By optimizing the scheduling algorithm, the performance of the system will be greatly improved.
