Cache.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. //
  2. // System.Web.Caching.Cache
  3. //
  4. // Author(s):
  5. // Lluis Sanchez ([email protected])
  6. //
  7. // (C) 2005 Novell, Inc (http://www.novell.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Threading;
  30. using System.Collections;
  31. using System.Security.Permissions;
  32. #if NET_2_0
  33. using System.Collections.Generic;
  34. #endif
  35. namespace System.Web.Caching
  36. {
  37. // CAS - no InheritanceDemand here as the class is sealed
  38. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. public sealed class Cache: IEnumerable
  40. {
  41. #if NET_2_0
  42. Dictionary <string, CacheItem> cache;
  43. #else
  44. Hashtable cache;
  45. #endif
  46. public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
  47. public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
  48. public Cache ()
  49. {
  50. #if NET_2_0
  51. cache = new Dictionary <string, CacheItem> ();
  52. #else
  53. cache = new Hashtable ();
  54. #endif
  55. }
  56. public int Count {
  57. get { return cache.Count; }
  58. }
  59. public object this [string key] {
  60. get { return Get (key); }
  61. set { Insert (key, value); }
  62. }
  63. public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  64. {
  65. if (key == null)
  66. throw new ArgumentNullException ("key");
  67. lock (cache) {
  68. CacheItem it;
  69. #if NET_2_0
  70. cache.TryGetValue (key, out it);
  71. #else
  72. it = (CacheItem) cache [key];
  73. #endif
  74. if (it != null)
  75. return it.Value;
  76. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
  77. }
  78. return null;
  79. }
  80. public object Get (string key)
  81. {
  82. lock (cache) {
  83. CacheItem it;
  84. #if NET_2_0
  85. if (!cache.TryGetValue (key, out it))
  86. return null;
  87. #else
  88. it = (CacheItem) cache [key];
  89. if (it == null)
  90. return null;
  91. #endif
  92. if (it.Dependency != null && it.Dependency.HasChanged) {
  93. Remove (it.Key, CacheItemRemovedReason.DependencyChanged);
  94. return null;
  95. }
  96. if (it.SlidingExpiration != NoSlidingExpiration) {
  97. it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
  98. it.Timer.Change ((int)it.SlidingExpiration.TotalMilliseconds, Timeout.Infinite);
  99. } else if (DateTime.Now >= it.AbsoluteExpiration) {
  100. Remove (key, CacheItemRemovedReason.Expired);
  101. return null;
  102. }
  103. return it.Value;
  104. }
  105. }
  106. public void Insert (string key, object value)
  107. {
  108. Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null);
  109. }
  110. public void Insert (string key, object value, CacheDependency dependencies)
  111. {
  112. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null);
  113. }
  114. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  115. {
  116. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null);
  117. }
  118. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  119. {
  120. if (key == null)
  121. throw new ArgumentNullException ("key");
  122. if (value == null)
  123. throw new ArgumentNullException ("value");
  124. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  125. throw new ArgumentNullException ("slidingExpiration");
  126. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  127. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  128. CacheItem ci = new CacheItem ();
  129. ci.Value = value;
  130. ci.Key = key;
  131. if (dependencies != null) {
  132. ci.Dependency = dependencies;
  133. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  134. dependencies.SetCache (this);
  135. }
  136. ci.SlidingExpiration = slidingExpiration;
  137. if (slidingExpiration != NoSlidingExpiration)
  138. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  139. else
  140. ci.AbsoluteExpiration = absoluteExpiration;
  141. ci.Priority = priority;
  142. ci.OnRemoveCallback = onRemoveCallback;
  143. lock (cache) {
  144. cache [key] = ci;
  145. ci.LastChange = DateTime.Now;
  146. if (ci.AbsoluteExpiration != NoAbsoluteExpiration) {
  147. int remaining = Math.Max (0, (int)(ci.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  148. ci.Timer = new Timer (new TimerCallback (ItemExpired), ci, remaining, Timeout.Infinite);
  149. }
  150. }
  151. }
  152. public object Remove (string key)
  153. {
  154. return Remove (key, CacheItemRemovedReason.Removed);
  155. }
  156. object Remove (string key, CacheItemRemovedReason reason)
  157. {
  158. lock (cache) {
  159. CacheItem it;
  160. #if NET_2_0
  161. cache.TryGetValue (key, out it);
  162. #else
  163. it = (CacheItem) cache [key];
  164. #endif
  165. if (it != null) {
  166. if (it.Dependency != null) {
  167. #if NET_2_0
  168. it.Dependency.SetCache (null);
  169. #endif
  170. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  171. it.Dependency.Dispose ();
  172. }
  173. cache.Remove (key);
  174. if (it.OnRemoveCallback != null) {
  175. try {
  176. it.OnRemoveCallback (key, it.Value, reason);
  177. } catch {
  178. //TODO: anything to be done here?
  179. }
  180. }
  181. return it.Value;
  182. } else
  183. return null;
  184. }
  185. }
  186. // Used when shutting down the application so that
  187. // session_end events are sent for all sessions.
  188. internal void InvokePrivateCallbacks ()
  189. {
  190. CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
  191. lock (cache) {
  192. foreach (string key in cache.Keys) {
  193. CacheItem item;
  194. #if NET_2_0
  195. cache.TryGetValue (key, out item);
  196. #else
  197. item = (CacheItem) cache [key];
  198. #endif
  199. if (item != null && item.OnRemoveCallback != null) {
  200. try {
  201. item.OnRemoveCallback (key, item.Value, reason);
  202. } catch {
  203. //TODO: anything to be done here?
  204. }
  205. }
  206. }
  207. }
  208. }
  209. public IDictionaryEnumerator GetEnumerator ()
  210. {
  211. ArrayList list = new ArrayList ();
  212. lock (cache) {
  213. #if NET_2_0
  214. foreach (CacheItem it in cache.Values)
  215. list.Add (it);
  216. #else
  217. list.AddRange (cache.Values);
  218. #endif
  219. }
  220. return new CacheItemEnumerator (list);
  221. }
  222. IEnumerator IEnumerable.GetEnumerator ()
  223. {
  224. return GetEnumerator ();
  225. }
  226. void OnDependencyChanged (object o, EventArgs a)
  227. {
  228. CheckDependencies ();
  229. }
  230. void ItemExpired(object cacheItem) {
  231. CacheItem ci = (CacheItem)cacheItem;
  232. ci.Timer.Dispose();
  233. ci.Timer = null;
  234. Remove(ci.Key, CacheItemRemovedReason.Expired);
  235. }
  236. internal void CheckDependencies ()
  237. {
  238. ArrayList list;
  239. lock (cache) {
  240. list = new ArrayList ();
  241. #if NET_2_0
  242. foreach (CacheItem it in cache.Values)
  243. list.Add (it);
  244. #else
  245. list.AddRange (cache.Values);
  246. #endif
  247. }
  248. foreach (CacheItem it in list) {
  249. if (it.Dependency != null && it.Dependency.HasChanged)
  250. Remove (it.Key, CacheItemRemovedReason.DependencyChanged);
  251. }
  252. }
  253. internal DateTime GetKeyLastChange (string key)
  254. {
  255. lock (cache) {
  256. CacheItem it;
  257. #if NET_2_0
  258. cache.TryGetValue (key, out it);
  259. #else
  260. it = (CacheItem) cache [key];
  261. #endif
  262. if (it == null) return DateTime.MaxValue;
  263. return it.LastChange;
  264. }
  265. }
  266. }
  267. class CacheItem
  268. {
  269. public object Value;
  270. public string Key;
  271. public CacheDependency Dependency;
  272. public DateTime AbsoluteExpiration;
  273. public TimeSpan SlidingExpiration;
  274. public CacheItemPriority Priority;
  275. public CacheItemRemovedCallback OnRemoveCallback;
  276. public DateTime LastChange;
  277. public Timer Timer;
  278. }
  279. class CacheItemEnumerator: IDictionaryEnumerator
  280. {
  281. ArrayList list;
  282. int pos = -1;
  283. public CacheItemEnumerator (ArrayList list)
  284. {
  285. this.list = list;
  286. }
  287. CacheItem Item {
  288. get {
  289. if (pos < 0 || pos >= list.Count)
  290. throw new InvalidOperationException ();
  291. return (CacheItem) list [pos];
  292. }
  293. }
  294. public DictionaryEntry Entry {
  295. get { return new DictionaryEntry (Item.Key, Item.Value); }
  296. }
  297. public object Key {
  298. get { return Item.Key; }
  299. }
  300. public object Value {
  301. get { return Item.Value; }
  302. }
  303. public object Current {
  304. get { return Entry; }
  305. }
  306. public bool MoveNext ()
  307. {
  308. return (++pos < list.Count);
  309. }
  310. public void Reset ()
  311. {
  312. pos = -1;
  313. }
  314. }
  315. }