search
HomeBackend DevelopmentC#.Net TutorialAn example of how .net uses the Cache framework
An example of how .net uses the Cache frameworkJul 24, 2017 pm 08:01 PM
.netcacheExample

        .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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python中的SVM实例Python中的SVM实例Jun 11, 2023 pm 08:42 PM

Python中的支持向量机(SupportVectorMachine,SVM)是一个强大的有监督学习算法,可以用来解决分类和回归问题。SVM在处理高维度数据和非线性问题的时候表现出色,被广泛地应用于数据挖掘、图像分类、文本分类、生物信息学等领域。在本文中,我们将介绍在Python中使用SVM进行分类的实例。我们将使用scikit-learn库中的SVM模

入职后,我才明白什么叫Cache入职后,我才明白什么叫CacheJul 31, 2023 pm 04:03 PM

事情其实是这样的,当时领导交给我一个perf硬件性能监视的任务,在使用perf的过程中,输入命令perf list,我看到了以下信息:我的任务就要让这些cache事件能够正常计数,但关键是,我根本不知道这些misses、loads是什么意思。

分享几个.NET开源的AI和LLM相关项目框架分享几个.NET开源的AI和LLM相关项目框架May 06, 2024 pm 04:43 PM

当今人工智能(AI)技术的发展如火如荼,它们在各个领域都展现出了巨大的潜力和影响力。今天大姚给大家分享4个.NET开源的AI模型LLM相关的项目框架,希望能为大家提供一些参考。https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel是一种开源的软件开发工具包(SDK),旨在将大型语言模型(LLM)如OpenAI、Azure

C#的就业前景如何C#的就业前景如何Oct 19, 2023 am 11:02 AM

无论您是初学者还是有经验的专业人士,掌握C#将为您的职业发展铺平道路。

使用cache可以提高计算机运行速度这是因为什么使用cache可以提高计算机运行速度这是因为什么Dec 09, 2020 am 11:28 AM

使用cache可以提高计算机运行速度这是因为Cache缩短了CPU的等待时间。Cache是位于CPU和主存储器DRAM之间,规模较小,但速度很高的存储器。Cache的功能是提高CPU数据输入输出的速率;Cache容量小但速度快,内存速度较低但容量大,通过优化调度算法,系统的性能会大大改善。

cache是什么存储器?cache是什么存储器?Nov 25, 2022 am 11:48 AM

cache叫做高速缓冲存储器,是介于中央处理器和主存储器之间的高速小容量存储器,一般由高速SRAM构成;这种局部存储器是面向CPU的,引入它是为减小或消除CPU与内存之间的速度差异对系统性能带来的影响。Cache容量小但速度快,内存速度较低但容量大,通过优化调度算法,系统的性能会大大改善。

nginx反向代理缓存教程。nginx反向代理缓存教程。Feb 18, 2024 pm 04:48 PM

以下是nginx反向代理缓存的教程:安装nginx:sudoaptupdatesudoaptinstallnginx配置反向代理:打开nginx配置文件:sudonano/etc/nginx/nginx.conf在http块中添加以下配置来启用缓存:http{...proxy_cache_path/var/cache/nginxlevels=1:2keys_zone=my_cache:10mmax_size=10ginactive=60muse_temp_path=off;proxy_cache

VUE3入门实例:制作一个简单的视频播放器VUE3入门实例:制作一个简单的视频播放器Jun 15, 2023 pm 09:42 PM

随着新一代前端框架的不断涌现,VUE3作为一个快速、灵活、易上手的前端框架备受热爱。接下来,我们就来一起学习VUE3的基础知识,制作一个简单的视频播放器。一、安装VUE3首先,我们需要在本地安装VUE3。打开命令行工具,执行以下命令:npminstallvue@next接着,新建一个HTML文件,引入VUE3:&lt;!doctypehtml&gt;

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.