当前位置: 首页 > news >正文

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,}
http://www.lryc.cn/news/366487.html

相关文章:

  • 【学习笔记】Linux前置准备
  • 各种空气能热泵安装图
  • 软件杯 题目:基于深度学习的中文对话问答机器人
  • UI学习笔记(一)
  • 【C语言训练题库】扫雷->简单小游戏!
  • WMS仓储管理系统高效驱动制造企业物料管理
  • python使用appium打开程序后,为什么没有操作后程序就自动退出了
  • MacBook M系列芯片安装php8.2
  • OlSoul系统调校程序v2024.06.05
  • 图像特征提取 python
  • width: 100%和 width: 100vw这两种写法有什么区别
  • 如何在另一台电脑上使用相同的Python环境和依赖包
  • Vue3 响应式 API:工具函数(一)
  • 开发常用软件
  • conntrack如何限制您的k8s网关
  • SwiftUI六组合复杂用户界面
  • 高考分数查询结果自动推送至微信
  • flask_sqlalchemy时间缓存导致datetime.now()时间不变问题
  • 使用 PAI-DSW x Free Prompt Editing图像编辑算法,开发个人AIGC绘图小助理
  • Nginx03-动态资源和LNMP介绍与实验、自动索引模块、基础认证模块、状态模块
  • 山东大学软件学院项目实训-创新实训-基于大模型的旅游平台(二十九)- 微服务(9)
  • Matplotlib常见图汇总
  • MTK联发科MT6897(天玑8300)5G智能移动处理器规格参数
  • 【AIoT-Robot】3d hand pose
  • 使用 tc (Traffic Control)控制网络延时
  • android原生TabLayout之自定义指示器效果
  • 最新 HUAWEI DevEco Studio 使用技巧
  • 开源大模型与闭源大模型浅析
  • docker 命令 ps,inspect,top,logs详解
  • Windows 找不到文件‘shell:sendto‘。请确定文件名是否正确后,再试一次