首页 > 代码库 > .Net牛刀小试-1缓冲使用

.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 = http://www.mamicode.com/cache.getCache();    

 

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