search
HomeBackend DevelopmentC#.Net TutorialAn example of how .net uses the Cache framework

An example of how .net uses the Cache framework

Jul 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
C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.