【wpf】缓存

本文介绍如何使用.NET Framework中的MemoryCache类来缓存文件的内容,并设置了缓存项的有效期为10秒。首先实例化了MemoryCache类,然后检查缓存中是否存在所需的数据,若不存在则从文件中读取内容并将其存储到缓存中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、引用 System.Runtime.Caching

2、源 msdn

 1 //实例化MemoryCache类
 2             ObjectCache cache = MemoryCache.Default;
 3             //读取缓存
 4             string fileContents = cache["filecontents"] as string;
 5             if (fileContents == null)
 6             {
 7                 StringBuilder strb = new StringBuilder();
 8                 path = AppDomain.CurrentDomain.BaseDirectory + "Resources/caching.txt";
 9                 //读取文件内容
10                 StreamReader sr = new StreamReader(path, Encoding.Default);
11                 String line;
12                 while ((line = sr.ReadLine()) != null)
13                 {
14                     strb.Append(line.ToString());
15                 }
16                 fileContents = strb.ToString() + "---" + DateTime.Now;
17                 //设置缓存过期时间
18                 CacheItemPolicy policy = new CacheItemPolicy();
19                 policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);
20 
21                 List<string> filePaths = new List<string>();
22                 filePaths.Add(path);
23                 //添加缓存
24                 cache.Set("filecontents", fileContents, policy);
25             }

 

转载于:https://www.cnblogs.com/oiliu/p/5505079.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值