缓存-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;  
}
复制代码

 

 
 
 
 
 

 

posted on   荆棘人  阅读(292)  评论(0编辑  收藏  举报

编辑推荐:
· 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区别

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示