缓存-MemoryCache Class
这是使用MemoryCache缓存的一个例子。
private void btnGet_Click(object sender, EventArgs e) { ObjectCache cache = MemoryCache.Default; string fileContents = cache["filecontents"] as string; if (fileContents == null) { CacheItemPolicy policy = new CacheItemPolicy(); List<string> filePaths = new List<string>(); filePaths.Add("c:\\cache\\example.txt"); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); // Fetch the file contents. fileContents = File.ReadAllText("c:\\cache\\example.txt"); cache.Set("filecontents", fileContents, policy); } Label1.Text = fileContents; }
最早在.NET Framework中实现了 MemoryCache类,继承自ObjectCache。
最早只有asp.net中有缓存类Namespace:System.Web.Caching,但是该类不适合在 ASP.NET 应用程序外部使用。
以上资料来自:Docs .NET .NET API 浏览器 System.Web.Caching Cache
地址:https://docs.microsoft.com/zh-cn/dotnet/api/system.web.caching.cache?view=netframework-4.7.2
---------------------------
20190807
Cache类不适合在 ASP.NET 应用程序外部使用。 它是设计和测试在提供的 Web 应用程序中缓存的 ASP.NET 中使用。
对于其他类型的应用程序,如控制台应用程序或 Windows 窗体应用程序,请使用ObjectCache类。
内置MemoryCache类派生自ObjectCache类。 MemoryCache类是中的唯一具体对象缓存实现.NET Framework 4派生ObjectCache类。
MemoryCache 不是单一实例,但您应创建仅几个或者可能仅一个MemoryCache实例和缓存项的代码应使用这些实例。
示例代码
private void btnGet_Click(object sender, EventArgs e) { ObjectCache cache = MemoryCache.Default; string fileContents = cache["filecontents"] as string; if (fileContents == null) { CacheItemPolicy policy = new CacheItemPolicy(); List<string> filePaths = new List<string>(); filePaths.Add("c:\\cache\\example.txt"); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); // Fetch the file contents. fileContents = File.ReadAllText("c:\\cache\\example.txt"); cache.Set("filecontents", fileContents, policy); } Label1.Text = fileContents; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2017-11-22 服务器性能指标有哪些
2017-11-22 C#一些需要注意的点(中级)
2017-11-22 JSON.parse与eval区别