Cache.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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, false);
  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, false);
  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, false);
  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, true);
  110. }
  111. public void Insert (string key, object value, CacheDependency dependencies)
  112. {
  113. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
  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, true);
  118. }
  119. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  120. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  121. {
  122. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, onRemoveCallback, true);
  123. }
  124. void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  125. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, bool doLock)
  126. {
  127. if (key == null)
  128. throw new ArgumentNullException ("key");
  129. if (value == null)
  130. throw new ArgumentNullException ("value");
  131. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  132. throw new ArgumentNullException ("slidingExpiration");
  133. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  134. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  135. CacheItem ci = new CacheItem ();
  136. ci.Value = value;
  137. ci.Key = key;
  138. if (dependencies != null) {
  139. ci.Dependency = dependencies;
  140. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  141. dependencies.SetCache (DependencyCache);
  142. }
  143. ci.Priority = priority;
  144. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, key, doLock);
  145. }
  146. internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
  147. {
  148. CacheItem ci = null;
  149. try {
  150. if (doLock)
  151. Monitor.Enter (cache);
  152. #if NET_2_0
  153. cache.TryGetValue (key, out ci);
  154. #else
  155. ci = (CacheItem) cache [key];
  156. #endif
  157. if (ci != null)
  158. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, false);
  159. } finally {
  160. if (doLock)
  161. Monitor.Exit (cache);
  162. }
  163. }
  164. void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback,
  165. string key, bool doLock)
  166. {
  167. ci.SlidingExpiration = slidingExpiration;
  168. if (slidingExpiration != NoSlidingExpiration)
  169. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  170. else
  171. ci.AbsoluteExpiration = absoluteExpiration;
  172. ci.OnRemoveCallback = onRemoveCallback;
  173. try {
  174. if (doLock)
  175. Monitor.Enter (cache);
  176. if (ci.Timer != null) {
  177. ci.Timer.Dispose ();
  178. ci.Timer = null;
  179. }
  180. if (key != null)
  181. cache [key] = ci;
  182. ci.LastChange = DateTime.Now;
  183. if (ci.AbsoluteExpiration != NoAbsoluteExpiration) {
  184. int remaining = Math.Max (0, (int)(ci.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  185. ci.Timer = new Timer (new TimerCallback (ItemExpired), ci, remaining, Timeout.Infinite);
  186. }
  187. } finally {
  188. if (doLock)
  189. Monitor.Exit (cache);
  190. }
  191. }
  192. public object Remove (string key)
  193. {
  194. return Remove (key, CacheItemRemovedReason.Removed, true);
  195. }
  196. object Remove (string key, CacheItemRemovedReason reason, bool doLock)
  197. {
  198. CacheItem it = null;
  199. try {
  200. if (doLock)
  201. Monitor.Enter (cache);
  202. #if NET_2_0
  203. cache.TryGetValue (key, out it);
  204. #else
  205. it = (CacheItem) cache [key];
  206. #endif
  207. cache.Remove (key);
  208. } finally {
  209. if (doLock)
  210. Monitor.Exit (cache);
  211. }
  212. if (it != null) {
  213. Timer t = it.Timer;
  214. if (t != null)
  215. t.Dispose ();
  216. if (it.Dependency != null) {
  217. #if NET_2_0
  218. it.Dependency.SetCache (null);
  219. #endif
  220. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  221. it.Dependency.Dispose ();
  222. }
  223. if (it.OnRemoveCallback != null) {
  224. try {
  225. it.OnRemoveCallback (key, it.Value, reason);
  226. } catch {
  227. //TODO: anything to be done here?
  228. }
  229. }
  230. return it.Value;
  231. } else
  232. return null;
  233. }
  234. // Used when shutting down the application so that
  235. // session_end events are sent for all sessions.
  236. internal void InvokePrivateCallbacks ()
  237. {
  238. CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
  239. lock (cache) {
  240. foreach (string key in cache.Keys) {
  241. CacheItem item;
  242. #if NET_2_0
  243. cache.TryGetValue (key, out item);
  244. #else
  245. item = (CacheItem) cache [key];
  246. #endif
  247. if (item != null && item.OnRemoveCallback != null) {
  248. try {
  249. item.OnRemoveCallback (key, item.Value, reason);
  250. } catch {
  251. //TODO: anything to be done here?
  252. }
  253. }
  254. }
  255. }
  256. }
  257. public IDictionaryEnumerator GetEnumerator ()
  258. {
  259. ArrayList list = new ArrayList ();
  260. lock (cache) {
  261. #if NET_2_0
  262. foreach (CacheItem it in cache.Values)
  263. list.Add (it);
  264. #else
  265. list.AddRange (cache.Values);
  266. #endif
  267. }
  268. return new CacheItemEnumerator (list);
  269. }
  270. IEnumerator IEnumerable.GetEnumerator ()
  271. {
  272. return GetEnumerator ();
  273. }
  274. void OnDependencyChanged (object o, EventArgs a)
  275. {
  276. CheckDependencies ();
  277. }
  278. void ItemExpired(object cacheItem) {
  279. CacheItem ci = (CacheItem)cacheItem;
  280. ci.Timer.Dispose();
  281. ci.Timer = null;
  282. Remove (ci.Key, CacheItemRemovedReason.Expired, true);
  283. }
  284. internal void CheckDependencies ()
  285. {
  286. ArrayList list;
  287. lock (cache) {
  288. list = new ArrayList ();
  289. #if NET_2_0
  290. foreach (CacheItem it in cache.Values)
  291. list.Add (it);
  292. #else
  293. list.AddRange (cache.Values);
  294. #endif
  295. foreach (CacheItem it in list) {
  296. if (it.Dependency != null && it.Dependency.HasChanged)
  297. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false);
  298. }
  299. }
  300. }
  301. internal DateTime GetKeyLastChange (string key)
  302. {
  303. lock (cache) {
  304. CacheItem it;
  305. #if NET_2_0
  306. if (!cache.TryGetValue (key, out it))
  307. return DateTime.MaxValue;
  308. #else
  309. it = (CacheItem) cache [key];
  310. #endif
  311. if (it == null)
  312. return DateTime.MaxValue;
  313. return it.LastChange;
  314. }
  315. }
  316. internal Cache DependencyCache {
  317. get {
  318. if (dependencyCache == null)
  319. return this;
  320. return dependencyCache;
  321. }
  322. set { dependencyCache = value; }
  323. }
  324. }
  325. class CacheItem
  326. {
  327. public object Value;
  328. public string Key;
  329. public CacheDependency Dependency;
  330. public DateTime AbsoluteExpiration;
  331. public TimeSpan SlidingExpiration;
  332. public CacheItemPriority Priority;
  333. public CacheItemRemovedCallback OnRemoveCallback;
  334. public DateTime LastChange;
  335. public Timer Timer;
  336. }
  337. class CacheItemEnumerator: IDictionaryEnumerator
  338. {
  339. ArrayList list;
  340. int pos = -1;
  341. public CacheItemEnumerator (ArrayList list)
  342. {
  343. this.list = list;
  344. }
  345. CacheItem Item {
  346. get {
  347. if (pos < 0 || pos >= list.Count)
  348. throw new InvalidOperationException ();
  349. return (CacheItem) list [pos];
  350. }
  351. }
  352. public DictionaryEntry Entry {
  353. get { return new DictionaryEntry (Item.Key, Item.Value); }
  354. }
  355. public object Key {
  356. get { return Item.Key; }
  357. }
  358. public object Value {
  359. get { return Item.Value; }
  360. }
  361. public object Current {
  362. get { return Entry; }
  363. }
  364. public bool MoveNext ()
  365. {
  366. return (++pos < list.Count);
  367. }
  368. public void Reset ()
  369. {
  370. pos = -1;
  371. }
  372. }
  373. }