摘要:本文主要向大家介绍了C#编程之c# .Net 缓存 使用System.Runtime.Caching 做缓存 平滑过期,绝对过期,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之c# .Net 缓存 使用System.Runtime.Caching 做缓存 平滑过期,绝对过期,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
1 public class CacheHeloer
2 {
3
4 ///
7 private static CacheHeloer Default { get { return new CacheHeloer(); } }
8
9 ///
12 private MemoryCache cache = MemoryCache.Default;
13
14 ///
17 private object locker = new object();
18
19 ///
22 private CacheHeloer()
23 {
24 //CacheItemPolicy policy = new CacheItemPolicy(); //创建缓存项策略
25 ////过期时间设置,以下两种只能设置一种
26 //policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(5)); //设定某个时间过后将逐出缓存
27 //policy.SlidingExpiration = new TimeSpan(0, 0, 10); //设定某个时间段内未被访问将逐出缓存
28 ////逐出通知,以下两种只能设置一种
29 //policy.UpdateCallback = arguments => { Console.WriteLine("即将逐出缓存" + arguments.Key); };
30 }
31
32 ///
35 ///
36 ///
键
37 ///
38 public static object Get(string key)
39 {
40 return Default.GetFromCache(key);
41 }
42
43 ///
46 ///
47 ///
键
48 ///
49 private object GetFromCache(string key)
50 {
51 lock (locker)
52 {
53 if (cache.Contains(key))
54 {
55 return cache[key];
56 }
57 return null;
58 }
59 }
60
61 ///
64 ///
65 ///
键
66 ///
数据对象
67 ///
过期时间
68 public static bool Set(string key, Object value, TimeSpan expiresIn)
69 {
70 var policy = new CacheItemPolicy()
71 {
72 SlidingExpiration = expiresIn
73 };
74 return Default.SetToCache(key, value, policy);
75 }
76 ///
79 ///
80 ///
81 ///
82 ///
83 ///
84 public static bool Set(string key, Object value, DateTimeOffset expiresIn)
85 {
86 var policy = new CacheItemPolicy()
87 {
88 AbsoluteExpiration = expiresIn
89 };
90 return Default.SetToCache(key, value, policy);
91 }
92
93 ///
96 ///
97 ///
键
98 ///
值
99 ///
100 public static bool Set(string key, object value)
101 {
102 CacheItemPolicy policy = new CacheItemPolicy()
103 {
104 Priority = CacheItemPriority.NotRemovable,
105 };
106 return Default.SetToCache(key, value, policy);
107 }
108
109 ///
112 ///
113 ///
键
114 ///
数据对象
115 ///
过期时间
116 private bool SetToCache(string key, object value, CacheItemPolicy policy)
117 {
118 lock (locker)
119 {
120 cache.Set(key, value, policy);
121 return true;
122 }
123 }
124
125 ///
128 ///
129 public static ICollection
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号