.Net牛刀小试-1缓冲使用

根据文件名缓冲文件:

 

    /// <summary>
    /// 根据文件名缓冲指定目录文件
    /// </summary>
    public class FileCacheAdapter
    {
        private string CacheFilePath = string.Empty;
        public FileCacheAdapter(string cacheFilePath)
        {
            CacheFilePath = cacheFilePath;
        }
        public string getCache()
        {
            if (string.IsNullOrEmpty(CacheFilePath))
            {
                return "";
            }
            if (!File.Exists(CacheFilePath))
            {
                return "";
            }
            string cacheKey = Path.GetFileName(CacheFilePath);
            string result = MemoryCache.Default[cacheKey] as string;
            //如果没有命中缓冲,则初始化该缓冲
            if (result == null)
            {
                //缓冲过期策略
                var policy = new CacheItemPolicy();
                //设置过期时间
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);

                //初始化缓冲项变化检测集合
                var filePaths = new List<string>();
                filePaths.Add(CacheFilePath);
                policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));

                result = File.ReadAllText(CacheFilePath, Encoding.Default) + Environment.NewLine + DateTime.Now.ToString();
                MemoryCache.Default.Set(cacheKey, result, policy);
            }
            return result;
        }
    }

使用示例:

    string cacheFilePath = "e:\\cache\\cacheText.txt";
    var cache = new FileCacheAdapter(cacheFilePath);
    string data = cache.getCache();    

 

转载于:https://www.cnblogs.com/moulton/p/6589693.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值