【C#】缓存数据
- namespace WpfCopy.Controls
- {
- public class CacheFileEventArgs : EventArgs
- {
- public bool IsFaulted { get; private set; }
- public CacheFileModel CacheFile { get; private set; }
- public CacheFileEventArgs(CacheFileModel cacheFile)
- {
- CacheFile = cacheFile;
- IsFaulted = false;
- }
- public CacheFileEventArgs()
- {
- IsFaulted = true;
- }
- }
- public class CacheFileModel
- {
- public string RemoteFile { get; set; }
- public string LocalFile { get; set; }
- public DateTime CreateTime { get; set; }
- public DateTime LastUseTime { get; set; }
- }
- class FileCacheMgr
- {
- private const string CacheDir = "CacheFile";
- private const string CacheDataFile = "file.cache";
- /// <summary>
- /// 缓存数据文件的读写锁
- /// </summary>
- readonly object _cacheDataFileLock = new object();
- /// <summary>
- /// 管理缓存数据的锁
- /// </summary>
- readonly object _cacheLock = new object();
- /// <summary>
- /// 缓存数据任务的锁
- /// </summary>
- readonly object _cacheTaskLock = new object();
- /// <summary>
- /// 缓存数据字典
- /// </summary>
- Dictionary<string, CacheFileModel> _cacheDict = new Dictionary<string, CacheFileModel>();
- /// <summary>
- /// 下载任务字典
- /// </summary>
- readonly Dictionary<string, WeakDelegateCollection<CacheFileEventArgs>> _cacheTaskDict = new Dictionary<string, WeakDelegateCollection<CacheFileEventArgs>>();
- private static readonly FileCacheMgr instance = new FileCacheMgr();
- public static FileCacheMgr Instance { get { return instance; } }
- public FileCacheMgr()
- {
- }
- /// <summary>
- /// 读取缓存
- /// </summary>
- void LoadCacheData()
- {
- lock (_cacheDataFileLock)
- {
- if (!File.Exists(CacheDataFile) && Directory.Exists(CacheDir))
- Directory.Delete(CacheDir, true);
- var xs = new XmlSerializer(typeof(List<CacheFileModel>));
- using (Stream stream = new FileStream(CacheDataFile, FileMode.Open, FileAccess.Read))
- {
- var list = xs.Deserialize(stream) as List<CacheFileModel> ?? new List<CacheFileModel>();
- _cacheDict = list.ToDictionary(m => m.RemoteFile);
- }
- }
- }
- /// <summary>
- /// 保存缓存
- /// </summary>
- void SaveCacheData()
- {
- lock (_cacheDataFileLock)
- {
- try
- {
- var xs = new XmlSerializer(typeof(List<CacheFileModel>));
- using (Stream stream = new FileStream(CacheDataFile, FileMode.Create, FileAccess.Write))
- {
- xs.Serialize(stream, _cacheDict.Values.ToList<CacheFileModel>());
- }
- }
- catch (Exception)
- {
- File.Delete(CacheDataFile);
- }
- }
- }
- /// <summary>
- /// 清除过期缓存
- /// </summary>
- public void ClearExpireCache()
- {
- try
- {
- List<string> clearList = new List<string>();
- foreach (var item in _cacheDict)
- {
- if (DateTime.Now - item.Value.LastUseTime > TimeSpan.FromDays(7))
- clearList.Add(item.Key);
- }
- foreach (var item in clearList)
- {
- File.Delete(_cacheDict[item].LocalFile);
- _cacheDict.Remove(item);
- }
- SaveCacheData();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 添加缓存数据
- /// </summary>
- /// <param name="model"></param>
- public void AddCacheData(CacheFileModel model)
- {
- if (model == null)
- throw new ArgumentException("model");
- lock (_cacheLock)
- {
- if (_cacheDict.ContainsKey(model.RemoteFile) == false)
- {
- _cacheDict.Add(model.RemoteFile, model);
- SaveCacheData();
- }
- }
- }
- /// <summary>
- /// 删除缓存文件--
- /// </summary>
- /// <param name="model"></param>
- public void RemoveCacheData(CacheFileModel model)
- {
- if (model == null)
- throw new ArgumentException("model");
- if (File.Exists(model.LocalFile))
- File.Delete(model.LocalFile);
- if (_cacheDict.ContainsKey(model.RemoteFile))
- {
- _cacheDict.Remove(model.RemoteFile);
- SaveCacheData();
- }
- }
- /// <summary>
- /// 获取缓存数据,如果不存在,则创建下载任务
- /// </summary>
- /// <param name="remoteFile"></param>
- /// <param name="callback"></param>
- /// <param name="getFtpFunc"></param>
- void GetCacheFile(string remoteFile, EventHandler<CacheFileEventArgs> callback, Func<MyFtp> getFtpFunc)
- {
- if (_cacheDict.ContainsKey(remoteFile))
- {
- CacheFileModel cache = _cacheDict[remoteFile];
- if (File.Exists(cache.LocalFile))
- {
- cache.LastUseTime = DateTime.Now;
- SaveCacheData();
- if (callback != null)
- {
- callback(this, new CacheFileEventArgs(cache));
- }
- return;
- }
- else
- {
- _cacheDict.Remove(remoteFile);
- }
- }
- CreateDownLoadTask(remoteFile, getFtpFunc(), callback);
- }
- void CreateDownLoadTask(string remoteFile, MyFtp myFtp, EventHandler<CacheFileEventArgs> callBack)
- {
- lock (_cacheTaskLock)
- {
- bool exist = _cacheTaskDict.ContainsKey(remoteFile);
- AddCallBackToDictNoLock(remoteFile, callBack);
- if (exist == false)
- {
- Task.Factory.StartNew(() =>
- {
- DownloadFileWork(remoteFile, myFtp, callBack);
- }, TaskCreationOptions.PreferFairness);
- }
- }
- }
- void DownloadFileWork(string remoteFile, MyFtp myFtp, EventHandler<CacheFileEventArgs> callback)
- {
- string localFile = Path.Combine(CacheDir, Guid.NewGuid().ToString() + Path.GetExtension(remoteFile));
- string path = Path.GetDirectoryName(localFile);
- if (Directory.Exists(path) == false)
- {
- Directory.CreateDirectory(path);
- }
- var eventArgs = new CacheFileEventArgs();
- try
- {
- bool dlRet = myFtp.DownLoad(remoteFile, localFile);
- if (dlRet && File.Exists(localFile))
- {
- var cacheModel = new CacheFileModel()
- {
- RemoteFile = remoteFile,
- LocalFile = localFile
- };
- eventArgs = new CacheFileEventArgs(cacheModel);
- AddCacheData(cacheModel);
- }
- }
- finally
- {
- try
- {
- InvokeCallBack(remoteFile, eventArgs);
- }
- finally
- {
- RemoveCallBack(remoteFile);
- }
- }
- }
- void AddCallBackToDictNoLock(string remoteFile, EventHandler<CacheFileEventArgs> callback)
- {
- if (_cacheTaskDict.ContainsKey(remoteFile) == false)
- _cacheTaskDict.Add(remoteFile, new WeakDelegateCollection<CacheFileEventArgs>());
- var weakEvent = _cacheTaskDict[remoteFile];
- weakEvent.WeakEvent += callback;
- }
- void RemoveCallBack(string remoteFile)
- {
- lock (_cacheTaskLock)
- {
- if (_cacheTaskDict.ContainsKey(remoteFile))
- _cacheTaskDict.Remove(remoteFile);
- }
- }
- void InvokeCallBack(string remoteFile, CacheFileEventArgs args)
- {
- lock (_cacheTaskLock)
- {
- if (_cacheTaskDict.ContainsKey(remoteFile) == false)
- {
- return;
- }
- _cacheTaskDict[remoteFile].Invoke(this, args);
- }
- }
- }
- }
【C#】缓存数据的更多相关文章
- plain framework 1 网络流 缓存数据详解
网络流是什么?为什么网络流中需要存在缓存数据?为什么PF中要采用缓存网络数据的机制?带着这几个疑问,让我们好好详细的了解一下在网络数据交互中我们容易忽视以及薄弱的一块.该部分为PF现有的网络流模型,但 ...
- thinkphp 缓存数据
thinkphp 中内置了缓存操作 3.1版本的数据缓存方法是cache 基本用法: S(array('type'=>'xcache','expire'=>60)); 缓存初始化 缓存初始 ...
- HTML5本地缓存数据
//HTML5本地缓存数据 function putObj(key, data) { if (!!window.localStorage) { var obj = { "key": ...
- 刷新本地的DNS缓存数据
ipconfig /flushdns”执行,刷新本地的DNS缓存数据. ipconfig /displaydns 查看本地DNS缓存记录的命令为:ipconfig /displaydns.你 ...
- 网站缓存数据到tomcat服务器
通过缓存使相同的数据不用重复加载,降低数据库的访问 public class CacheFilter implements Filter { //实例变量[每线程共享] private Map< ...
- iOS五种本地缓存数据方式
iOS五种本地缓存数据方式 iOS本地缓存数据方式有五种:前言 1.直接写文件方式:可以存储的对象有NSString.NSArray.NSDictionary.NSData.NSNumber,数据 ...
- IE浏览器中ajax使用缓存数据的问题
今天做了一个小功能:点击鼠标实时更新系统时间,采用ajax,过程很顺利,没遇到啥差错,谷歌,火狐,欧鹏一律通过,怀着忐忑的心情点开了IE8,果然,IE要对得起前端杀手的称号:更新不了时间. 查了一下这 ...
- Java通过SpyMemcached来缓存数据
配置好Magent+memcached后,很明显数据之间的输入与输出都是通过代理服务器的,magent是做代理服务器的很明显java在memecached的调用驱动在magent同样适用. 这里选择S ...
- ThinkPHP使用Memcached缓存数据
ThinkPHP默认使用文件缓存数据,支持Memcache等其他缓存方式,有两个PHP扩展:Memcache和Memcached,Memcahe官方有说明,主要说一下Memcached. 相对于PHP ...
- NCache实现Oracle数据与分布式缓存数据同步的3个步骤
多层次结构的应用程序是目前发展的趋势,这种程序都需要庞大的数据库支持.而数据传输的能力直接影响程序性能,成为程序可扩展性的瓶颈.因此很多开发者开始在程序中使用内存分布式缓存来提高程序性能. 同时,内存 ...
随机推荐
- array_diff使用注意
$lost_ids = array_diff($all_ids,$old_ids); //array_diff,$old_ids不可以为null否则返回为null;array_diff起不到效果~~~
- OpenCV---其他形态学操作
一:顶帽实现(原图像与开操作图像的差值) import cv2 as cv import numpy as np def top_hat_demo(image): gray = cv.cvtColor ...
- Vue 插槽详解
Vue插槽,是学习vue中必不可少的一节,当初刚接触vue的时候,对这些掌握的一知半解,特别是作用域插槽一直没明白. 后面越来越发现插槽的好用. 分享一下插槽的一些知识吧. 分一下几点: 1.插槽内可 ...
- 5W次单点修改,求最长的连续上升子序列 HDU 3308
题目大意:给你n个数,m个操作. 有两种操作: 1.U x y 将数组第x位变为y 2. Q x y 问数组第x位到第y位连续最长子序列的长度. 对于每次询问,输出连续最长子序列的长度 思路:用线段树 ...
- Why are Eight Bits Enough for Deep Neural Networks?
Why are Eight Bits Enough for Deep Neural Networks? Deep learning is a very weird technology. It evo ...
- Linux 操作系统下 VI 编辑器常用命令详细介绍
一.Vi 简介 vi是unix世界中最通用的全屏编辑器,linux中是用的是vi的加强版vim,vim同vi完全兼容,vi就是"visual interface"的缩写.它可以执行 ...
- 【Atcoer】ARC088 E - Papple Sort
[题目]E - Papple Sort [题意]给定长度为n的小写字母串,只能交换相邻字母,求形成回文串的最小步数.n<=2*10^5. [算法]数学 [题解]官方题解 本题题解中有以下重要的思 ...
- 莫比乌斯反演第二弹 入门 Coprime Integers Gym - 101982B
题目链接:https://cn.vjudge.net/problem/Gym-101982B 题目大意: 给你(a,b)和(c,d)这两个区间,然后问你这两个区间中互素的对数是多少. 具体思路:和我上 ...
- 阿里Java研发工程师实习面经,附面试技巧
作者:如何进阿里 链接:https://www.nowcoder.com/discuss/72899?type=0&order=0&pos=17&page=1 来源:牛客网 前 ...
- MySQL创建相同表和数据命令
创建和表departments结构和数据一样的表departments_t mysql> create table departments_t like departments; Query O ...