class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
//因为Instance是唯一的实例,所以其他类、任何地方调用
//FileCacheManager.Instance得到的都是同一个实例
string s1 =
FileCacheManager.Instance.ReadFile(@"c:\1.txt");
Console.WriteLine(s1);
Thread.Sleep(1);
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
}
}
//todo:做一个sqlhelper的缓存,根据sql语句为key
sealed class FileCacheManager
{
public static readonly FileCacheManager Instance
= new FileCacheManager();
private FileCacheManager()
{
}
//key是文件名,value是文件内容
//private Dictionary<string, string> dict
// = new Dictionary<string, string>();
private Dictionary<string, CacheItem> dict =
new Dictionary<string, CacheItem>();
public string ReadFile(string filename)
{
if (dict.ContainsKey(filename))
{
DateTime lastWriteTime = File.GetLastWriteTime(filename);
if (lastWriteTime == dict[filename].LastWriteTime)
{
return dict[filename].Content;
}
}
//走到这里说明缓存中没有数据或者文件被修改
string txt = File.ReadAllText(filename);
CacheItem item = new CacheItem();
item.Content = txt;
//把存缓存的时候的文件修改时间存起来
item.LastWriteTime = File.GetLastWriteTime(filename);
dict[filename] = item;
return txt;
//命令管理器读取文件的时候:判断文件是否已经读过了,如果读过了,
//直接讲存起来的值返回;如果没读过,则去读,并且把读出来的值存起来,然后返回。
//if (dict.ContainsKey(filename))
//{
// return dict[filename];
//}
//else
//{
// string txt = File.ReadAllText(filename);
// dict[filename] = txt;
// return txt;
//}
// return File.ReadAllText(filename);
}
}
class CacheItem
{
public string Content { get; set; }
public DateTime LastWriteTime { get; set; }
}