C# MemoryCache 缓存应用

摘要


缓存是一种非常常见的性能优化技术,在开发过程中经常会用到。.NET提供了内置的内存缓存类 MemoryCache,它可以很方便地存储数据并在后续的请求中快速读取,从而提高应用程序的响应速度。

正文


通过使用 Microsoft.Extensions.Caching.Memory,我们可以在 .NET Core 中轻松实现内存缓存功能,从而提高应用程序的性能和响应速度。在实际应用中,你可以根据具体需求来设置缓存的有效期和其他选项。

nuget 安装依赖 Microsoft.Extensions.Caching.Memory

图片

一个简单例子

public partial class Form1 : Form{    // 创建 MemoryCache 实例    MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
    System.Timers.Timer timer = new System.Timers.Timer();    int idx = 0;    public Form1()    {        InitializeComponent();        timer.Interval = 1000;        timer.Elapsed += (o, e) =>        {            this.Invoke(new Action(() =>            {                lblTime.Text = idx.ToString();                idx++;            }));        };    }
    private void btnCreateCache_Click(object sender, EventArgs e)    {        // 添加数据到缓存        string key = "hi";        string value = "Hello, World!";        var cacheEntryOptions = new MemoryCacheEntryOptions        {            AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1) // 缓存有效期为 1 分钟        };        cache.Set(key, value, cacheEntryOptions);        timer.Start();    }
    private void btnGetCache_Click(object sender, EventArgs e)    {        // 从缓存中获取数据        if (cache.TryGetValue("hi", out string cachedValue))        {            MessageBox.Show(cachedValue);        }        else        {            MessageBox.Show("没有找到cache");        }    }}

图片

/// <summary>/// 删除cache/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnDeleteCache_Click(object sender, EventArgs e){    cache.Remove("hi");}

  

缓存一个对象​​​​​​​

public class Person{    public string Name { get; set; }    
    public int Age { get; set; }
    public override string ToString()    {        return this.Name+" "+this.Age.ToString();    }}​​​​​​
public partial class Form1 : Form{    // 创建 MemoryCache 实例    MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
    System.Timers.Timer timer = new System.Timers.Timer();    int idx = 0;    public Form1()    {        InitializeComponent();        timer.Interval = 1000;        timer.Elapsed += (o, e) =>        {            this.Invoke(new Action(() =>            {                lblTime.Text = idx.ToString();                idx++;            }));        };    }
    private void btnCreateCache_Click(object sender, EventArgs e)    {        Person person = new Person()        {            Name="Rick",            Age=99        };
        // 添加对像数据到缓存        var cacheEntryOptions = new MemoryCacheEntryOptions        {            AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1) // 缓存有效期为 1 分钟        };        cache.Set<Person>("p1", person);        timer.Start();    }
    private void btnGetCache_Click(object sender, EventArgs e)    {        // 从缓存中获取数据        if (cache.TryGetValue<Person>("p1", out Person cachedValue))        {            MessageBox.Show(cachedValue.ToString());        }        else        {            MessageBox.Show("没有找到cache");        }    }
    /// <summary>    /// 删除cache    /// </summary>    /// <param name="sender"></param>    /// <param name="e"></param>    private void btnDeleteCache_Click(object sender, EventArgs e)    {        cache.Remove("p1");    }}

  

图片

侦听几个事件,使用PostEvictionCallbacks这个回调​​​​​​​

private void btnCreateCache_Click(object sender, EventArgs e){    Person person = new Person()    {        Name="Rick",        Age=99    };
    // 添加对像数据到缓存    var cacheEntryOptions = new MemoryCacheEntryOptions    {        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1), // 缓存有效期为 1 分钟        PostEvictionCallbacks =        {            new PostEvictionCallbackRegistration            {                EvictionCallback=Cache_EntryRemoved,                State =this            }        }    };    cache.Set<Person>("p1", person, cacheEntryOptions);    timer.Start();}
private static void Cache_EntryRemoved(object key, object value, EvictionReason reason, object state){    // 在 PostEvictionCallback 中处理逻辑    switch (reason.ToString())    {        case "Delete":            MessageBox.Show("删除缓存了!");            break;        default:            break;    }}

  

注意Reason,这里能知道是什么操作​​​​​​​

public enum EvictionReason{    None,
    /// <summary>    /// Manually    /// </summary>    Removed,
    /// <summary>    /// Overwritten    /// </summary>    Replaced,
    /// <summary>    /// Timed out    /// </summary>    Expired,
    /// <summary>    /// Event    /// </summary>    TokenExpired,
    /// <summary>    /// Overflow    /// </summary>    Capacity,}

相关推荐

  1. Flutter Web应用清理缓存

    2024-06-08 11:24:04       59 阅读
  2. ehcache3多级缓存应用

    2024-06-08 11:24:04       30 阅读
  3. 55.ReentrantReadWriteLock应用缓存

    2024-06-08 11:24:04       31 阅读
  4. 缓存击穿、缓存穿透、缓存雪崩以及应对措施

    2024-06-08 11:24:04       20 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-08 11:24:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-08 11:24:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-08 11:24:04       82 阅读
  4. Python语言-面向对象

    2024-06-08 11:24:04       91 阅读

热门阅读

  1. TypeScript记

    2024-06-08 11:24:04       19 阅读
  2. 每台云服务器最多可支持几块硬盘

    2024-06-08 11:24:04       31 阅读
  3. 篇3:Mapbox Style Specification

    2024-06-08 11:24:04       30 阅读
  4. selenium中,怎么进行浏览器的上下滚动

    2024-06-08 11:24:04       31 阅读
  5. 什么是PyTorch?PyTorch在生产环境中的部署策略

    2024-06-08 11:24:04       21 阅读
  6. mac前端com+f与com+shift+f查找文章内容

    2024-06-08 11:24:04       25 阅读
  7. 图论方法学习

    2024-06-08 11:24:04       30 阅读
  8. Tomcat 启动闪退问题解决方法

    2024-06-08 11:24:04       25 阅读
  9. tomcat 启动闪退问题解决方法

    2024-06-08 11:24:04       23 阅读
  10. Mysql 快速入门指南

    2024-06-08 11:24:04       23 阅读