Cache.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. Cache dependencyCache;
  47. public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
  48. public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
  49. public Cache ()
  50. {
  51. #if NET_2_0
  52. cache = new Dictionary <string, CacheItem> ();
  53. #else
  54. cache = new Hashtable ();
  55. #endif
  56. }
  57. public int Count {
  58. get { return cache.Count; }
  59. }
  60. public object this [string key] {
  61. get { return Get (key); }
  62. set { Insert (key, value); }
  63. }
  64. public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  65. {
  66. if (key == null)
  67. throw new ArgumentNullException ("key");
  68. lock (cache) {
  69. CacheItem it;
  70. #if NET_2_0
  71. cache.TryGetValue (key, out it);
  72. #else
  73. it = (CacheItem) cache [key];
  74. #endif
  75. if (it != null)
  76. return it.Value;
  77. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
  78. }
  79. return null;
  80. }
  81. public object Get (string key)
  82. {
  83. lock (cache) {
  84. CacheItem it;
  85. #if NET_2_0
  86. if (!cache.TryGetValue (key, out it))
  87. return null;
  88. #else
  89. it = (CacheItem) cache [key];
  90. if (it == null)
  91. return null;
  92. #endif
  93. if (it.Dependency != null && it.Dependency.HasChanged) {
  94. Remove (it.Key, CacheItemRemovedReason.DependencyChanged);
  95. return null;
  96. }
  97. if (it.SlidingExpiration != NoSlidingExpiration) {
  98. it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
  99. it.Timer.Change ((int)it.SlidingExpiration.TotalMilliseconds, Timeout.Infinite);
  100. } else if (DateTime.Now >= it.AbsoluteExpiration) {
  101. Remove (key, CacheItemRemovedReason.Expired);
  102. return null;
  103. }
  104. return it.Value;
  105. }
  106. }
  107. public void Insert (string key, object value)
  108. {
  109. Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null);
  110. }
  111. public void Insert (string key, object value, CacheDependency dependencies)
  112. {
  113. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null);
  114. }
  115. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  116. {
  117. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null);
  118. }
  119. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  120. {
  121. if (key == null)
  122. throw new ArgumentNullException ("key");
  123. if (value == null)
  124. throw new ArgumentNullException ("value");
  125. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  126. throw new ArgumentNullException ("slidingExpiration");
  127. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  128. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  129. CacheItem ci = new CacheItem ();
  130. ci.Value = value;
  131. ci.Key = key;
  132. if (dependencies != null) {
  133. ci.Dependency = dependencies;
  134. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  135. dependencies.SetCache (DependencyCache);
  136. }
  137. ci.Priority = priority;
  138. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, key);
  139. }
  140. internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  141. {
  142. CacheItem ci = null;
  143. lock (cache) {
  144. #if NET_2_0
  145. cache.TryGetValue (key, out ci);
  146. #else
  147. ci = (CacheItem) cache [key];
  148. #endif
  149. }
  150. if (ci != null)
  151. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null);
  152. }
  153. void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback, string key)
  154. {
  155. ci.SlidingExpiration = slidingExpiration;
  156. if (slidingExpiration != NoSlidingExpiration)
  157. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  158. else
  159. ci.AbsoluteExpiration = absoluteExpiration;
  160. ci.OnRemoveCallback = onRemoveCallback;
  161. lock (cache) {
  162. if (ci.Timer != null) {
  163. ci.Timer.Dispose ();
  164. ci.Timer = null;
  165. }
  166. if (key != null)
  167. cache [key] = ci;
  168. ci.LastChange = DateTime.Now;
  169. if (ci.AbsoluteExpiration != NoAbsoluteExpiration) {
  170. int remaining = Math.Max (0, (int)(ci.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  171. ci.Timer = new Timer (new TimerCallback (ItemExpired), ci, remaining, Timeout.Infinite);
  172. }
  173. }
  174. }
  175. public object Remove (string key)
  176. {
  177. return Remove (key, CacheItemRemovedReason.Removed);
  178. }
  179. object Remove (string key, CacheItemRemovedReason reason)
  180. {
  181. CacheItem it = null;
  182. lock (cache) {
  183. #if NET_2_0
  184. cache.TryGetValue (key, out it);
  185. #else
  186. it = (CacheItem) cache [key];
  187. #endif
  188. cache.Remove (key);
  189. }
  190. if (it != null) {
  191. if (it.Dependency != null) {
  192. #if NET_2_0
  193. it.Dependency.SetCache (null);
  194. #endif
  195. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  196. it.Dependency.Dispose ();
  197. }
  198. if (it.OnRemoveCallback != null) {
  199. try {
  200. it.OnRemoveCallback (key, it.Value, reason);
  201. } catch {
  202. //TODO: anything to be done here?
  203. }
  204. }
  205. return it.Value;
  206. } else
  207. return null;
  208. }
  209. // Used when shutting down the application so that
  210. // session_end events are sent for all sessions.
  211. internal void InvokePrivateCallbacks ()
  212. {
  213. CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
  214. lock (cache) {
  215. foreach (string key in cache.Keys) {
  216. CacheItem item;
  217. #if NET_2_0
  218. cache.TryGetValue (key, out item);
  219. #else
  220. item = (CacheItem) cache [key];
  221. #endif
  222. if (item != null && item.OnRemoveCallback != null) {
  223. try {
  224. item.OnRemoveCallback (key, item.Value, reason);
  225. } catch {
  226. //TODO: anything to be done here?
  227. }
  228. }
  229. }
  230. }
  231. }
  232. public IDictionaryEnumerator GetEnumerator ()
  233. {
  234. ArrayList list = new ArrayList ();
  235. lock (cache) {
  236. #if NET_2_0
  237. foreach (CacheItem it in cache.Values)
  238. list.Add (it);
  239. #else
  240. list.AddRange (cache.Values);
  241. #endif
  242. }
  243. return new CacheItemEnumerator (list);
  244. }
  245. IEnumerator IEnumerable.GetEnumerator ()
  246. {
  247. return GetEnumerator ();
  248. }
  249. void OnDependencyChanged (object o, EventArgs a)
  250. {
  251. CheckDependencies ();
  252. }
  253. void ItemExpired(object cacheItem) {
  254. CacheItem ci = (CacheItem)cacheItem;
  255. ci.Timer.Dispose();
  256. ci.Timer = null;
  257. Remove(ci.Key, CacheItemRemovedReason.Expired);
  258. }
  259. internal void CheckDependencies ()
  260. {
  261. ArrayList list;
  262. lock (cache) {
  263. list = new ArrayList ();
  264. #if NET_2_0
  265. foreach (CacheItem it in cache.Values)
  266. list.Add (it);
  267. #else
  268. list.AddRange (cache.Values);
  269. #endif
  270. }
  271. foreach (CacheItem it in list) {
  272. if (it.Dependency != null && it.Dependency.HasChanged)
  273. Remove (it.Key, CacheItemRemovedReason.DependencyChanged);
  274. }
  275. }
  276. internal DateTime GetKeyLastChange (string key)
  277. {
  278. lock (cache) {
  279. CacheItem it;
  280. #if NET_2_0
  281. cache.TryGetValue (key, out it);
  282. #else
  283. it = (CacheItem) cache [key];
  284. #endif
  285. if (it == null) return DateTime.MaxValue;
  286. return it.LastChange;
  287. }
  288. }
  289. internal Cache DependencyCache
  290. {
  291. get
  292. {
  293. if (dependencyCache == null)
  294. return this;
  295. return dependencyCache;
  296. }
  297. set { dependencyCache = value; }
  298. }
  299. }
  300. class CacheItem
  301. {
  302. public object Value;
  303. public string Key;
  304. public CacheDependency Dependency;
  305. public DateTime AbsoluteExpiration;
  306. public TimeSpan SlidingExpiration;
  307. public CacheItemPriority Priority;
  308. public CacheItemRemovedCallback OnRemoveCallback;
  309. public DateTime LastChange;
  310. public Timer Timer;
  311. }
  312. class CacheItemEnumerator: IDictionaryEnumerator
  313. {
  314. ArrayList list;
  315. int pos = -1;
  316. public CacheItemEnumerator (ArrayList list)
  317. {
  318. this.list = list;
  319. }
  320. CacheItem Item {
  321. get {
  322. if (pos < 0 || pos >= list.Count)
  323. throw new InvalidOperationException ();
  324. return (CacheItem) list [pos];
  325. }
  326. }
  327. public DictionaryEntry Entry {
  328. get { return new DictionaryEntry (Item.Key, Item.Value); }
  329. }
  330. public object Key {
  331. get { return Item.Key; }
  332. }
  333. public object Value {
  334. get { return Item.Value; }
  335. }
  336. public object Current {
  337. get { return Entry; }
  338. }
  339. public bool MoveNext ()
  340. {
  341. return (++pos < list.Count);
  342. }
  343. public void Reset ()
  344. {
  345. pos = -1;
  346. }
  347. }
  348. }