search
HomeBackend DevelopmentC#.Net TutorialAn example of how to add Cache to a program using the Cache framework in .net

这篇文章主要为大家详细介绍了使用.net的Cache框架快速实现Cache操作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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。

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;
  }

这个例子还是比较简单的,对于那些没有自定义的策略,则需要我们实现自己的ChangeMonitor。下次有时间在写篇文章更深入的介绍一下吧。

The above is the detailed content of An example of how to add Cache to a program using the Cache framework in .net. 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: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools