Cache.cs 11 KB

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