#region
class MyCachePool
{
ObjectCache cache = MemoryCache.Default;
const string CacheKey = "TestCacheKey";
//定义字符串类型常量CacheKey并赋初值为TestCacheKey,那么不能再改变CacheKey的值
//如执行CacheKey="2"; 就会运行错误在整个程序中 a的值始终为TestCacheKey
public string GetValue()
{
var content = cache[CacheKey] as string;
if(content == null)
{
Console.WriteLine("Get New Item");
//SlidingExpiration = TimeSpan.FromSeconds(3)
//第一种过期策略,当对象3秒钟内没有得到访问时,就会过期。如果对象一直被访问,则不会过期。
AbsoluteExpiration = DateTime.Now.AddSeconds(3)
//第二种过期策略,当超过3秒钟后,Cache内容就会过期。
content = Guid.NewGuid().ToString();
cache.Set(CacheKey, content, policy);
}
else
{
Console.WriteLine("Get cached item");
}
return content;
}
#endregion
static void Main(string[] args)
{
MyCachePool pool = new MyCachePool();
MyCachePool1 pool1 = new MyCachePool1();
while(true)
{
Thread.Sleep(1000);
var value = pool.GetValue();
//var value = pool1.myGetValue();
Console.WriteLine(value);
Console.WriteLine();
}
}
public string GetValue()
{
var content = cache[CacheKey] as string;
if(content == null)
{
Console.WriteLine("第二种过期方式");
var file = "C:\\Users\\Administrator\\Desktop\\test.txt";
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file }));
content = File.ReadAllText(file, Encoding.Default); //Encoding.Default用于解决乱码问题
//StreamReader sr = new StreamReader(file, Encoding.Default);
//content = sr.ReadToEnd();
//sr.Close();
//第二种读取方式
cache.Set(cacheKey, content, policy);
}
else
{
Console.WriteLine("Get cached item");
}
return content;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有