Cache.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. //
  2. // System.Web.Caching
  3. //
  4. // Author:
  5. // Patrik Torstensson ([email protected])
  6. // Changes:
  7. // Daniel Cazzulino [DHC] ([email protected])
  8. //
  9. // (C) Copyright Patrik Torstensson, 2001
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.Threading;
  14. namespace System.Web.Caching
  15. {
  16. /// <summary>
  17. /// Implements a cache for Web applications and other. The difference
  18. /// from the MS.NET implementation is that we / support to use the Cache
  19. /// object as cache in our applications.
  20. /// </summary>
  21. /// <remarks>
  22. /// The Singleton cache is created per application domain, and it
  23. /// remains valid as long as the application domain remains active.
  24. /// </remarks>
  25. /// <example>
  26. /// Usage of the singleton cache:
  27. ///
  28. /// Cache objManager = Cache.SingletonCache;
  29. ///
  30. /// String obj = "tobecached";
  31. /// objManager.Add("kalle", obj);
  32. /// </example>
  33. public sealed class Cache : IEnumerable
  34. {
  35. // Declarations
  36. /// <summary>
  37. /// Used in the absoluteExpiration parameter in an Insert
  38. /// method call to indicate the item should never expire. This
  39. /// field is read-only.
  40. /// </summary>
  41. public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
  42. /// <summary>
  43. /// Used as the slidingExpiration parameter in an Insert method
  44. /// call to disable sliding expirations. This field is read-only.
  45. /// </summary>
  46. public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
  47. // Helper objects
  48. CacheExpires _objExpires;
  49. // The data storage
  50. // Todo: Make a specialized storage for the cache entries?
  51. // todo: allow system to replace the storage?
  52. Hashtable _arrEntries;
  53. ReaderWriterLock _lockEntries;
  54. static TimeSpan _datetimeOneYear = TimeSpan.FromDays (365);
  55. int _nItems; // Number of items in the cache
  56. public Cache ()
  57. {
  58. _nItems = 0;
  59. _lockEntries = new ReaderWriterLock ();
  60. _arrEntries = new Hashtable ();
  61. _objExpires = new CacheExpires (this);
  62. }
  63. /// <summary>
  64. /// Internal method to create a enumerator and over all public
  65. /// items in the cache and is used by GetEnumerator method.
  66. /// </summary>
  67. /// <returns>
  68. /// Returns IDictionaryEnumerator that contains all public items in the cache
  69. /// </returns>
  70. private IDictionaryEnumerator CreateEnumerator ()
  71. {
  72. Hashtable objTable;
  73. //Locking with -1 provides a non-expiring lock.
  74. _lockEntries.AcquireReaderLock (-1);
  75. try {
  76. // Create a new hashtable to return as collection of public items
  77. objTable = new Hashtable (_arrEntries.Count);
  78. foreach (DictionaryEntry objEntry in _arrEntries) {
  79. if (objEntry.Key == null)
  80. continue;
  81. CacheEntry entry = (CacheEntry) objEntry.Value;
  82. if (entry.TestFlag (CacheEntry.Flags.Public))
  83. objTable.Add (objEntry.Key, entry.Item);
  84. }
  85. } finally {
  86. _lockEntries.ReleaseReaderLock ();
  87. }
  88. return objTable.GetEnumerator ();
  89. }
  90. /// <summary>
  91. /// Implementation of IEnumerable interface and calls the GetEnumerator that returns
  92. /// IDictionaryEnumerator.
  93. /// </summary>
  94. IEnumerator IEnumerable.GetEnumerator ()
  95. {
  96. return GetEnumerator ();
  97. }
  98. /// <summary>
  99. /// Virtual override of the IEnumerable.GetEnumerator() method,
  100. /// returns a specialized enumerator.
  101. /// </summary>
  102. public IDictionaryEnumerator GetEnumerator ()
  103. {
  104. return CreateEnumerator ();
  105. }
  106. /// <summary>
  107. /// Touches a object in the cache. Used to update expire time and hit count.
  108. /// </summary>
  109. /// <param name="strKey">The identifier for the cache item to retrieve.</param>
  110. internal void Touch(string strKey)
  111. {
  112. Get (strKey);
  113. }
  114. /// <summary>
  115. /// Adds the specified item to the Cache object with
  116. /// dependencies, expiration and priority policies, and a
  117. /// delegate you can use to notify your application when the
  118. /// inserted item is removed from the Cache.
  119. /// </summary>
  120. /// <param name="strKey">The cache key used to reference the item.</param>
  121. /// <param name="objItem">The item to be added to the cache.</param>
  122. /// <param name="objDependency">
  123. /// The file or cache key dependencies for the item. When any
  124. /// dependency changes, the object becomes invalid and is removed
  125. /// from the cache. If there are no dependencies, this paramter
  126. /// contains a null reference.
  127. /// </param>
  128. /// <param name="absolutExpiration">
  129. /// The time at which the added object expires and is removed from the cache.
  130. /// </param>
  131. /// <param name="slidingExpiration">
  132. /// The interval between the time the added object was last
  133. /// accessed and when that object expires. If this value is the
  134. /// equivalent of 20 minutes, the object expires and is removed
  135. /// from the cache 20 minutes after it is last accessed.
  136. /// </param>
  137. /// <param name="enumPriority">
  138. /// The relative cost of the object, as expressed by the
  139. /// CacheItemPriority enumeration. The cache uses this value when
  140. /// it evicts objects; objects with a lower cost are removed from
  141. /// the cache before objects with a higher cost.
  142. /// </param>
  143. /// <param name="eventRemoveCallback">
  144. /// A delegate that, if provided, is called when an object is
  145. /// removed from the cache. You can use this to notify
  146. /// applications when their objects are deleted from the
  147. /// cache.
  148. /// </param>
  149. /// <returns>The Object item added to the Cache.</returns>
  150. public object Add (string strKey,
  151. object objItem,
  152. CacheDependency objDependency,
  153. DateTime absolutExpiration,
  154. TimeSpan slidingExpiration,
  155. CacheItemPriority enumPriority,
  156. CacheItemRemovedCallback eventRemoveCallback)
  157. {
  158. return Add (strKey, objItem, objDependency, absolutExpiration,
  159. slidingExpiration, enumPriority, eventRemoveCallback, true);
  160. }
  161. private object Add (string strKey,
  162. object objItem,
  163. CacheDependency objDependency,
  164. DateTime absolutExpiration,
  165. TimeSpan slidingExpiration,
  166. CacheItemPriority enumPriority,
  167. CacheItemRemovedCallback eventRemoveCallback,
  168. bool pub)
  169. {
  170. if (strKey == null)
  171. throw new ArgumentNullException ("strKey");
  172. if (objItem == null)
  173. throw new ArgumentNullException ("objItem");
  174. if (slidingExpiration > _datetimeOneYear)
  175. throw new ArgumentOutOfRangeException ("slidingExpiration");
  176. CacheEntry objEntry;
  177. CacheEntry objNewEntry;
  178. long longHitRange = 10000;
  179. // todo: check decay and make up the minHit range
  180. objEntry = new CacheEntry (this,
  181. strKey,
  182. objItem,
  183. objDependency,
  184. eventRemoveCallback,
  185. absolutExpiration,
  186. slidingExpiration,
  187. longHitRange,
  188. pub,
  189. enumPriority);
  190. Interlocked.Increment (ref _nItems);
  191. // If we have any kind of expiration add into the CacheExpires class
  192. if (objEntry.HasSlidingExpiration || objEntry.HasAbsoluteExpiration)
  193. _objExpires.Add (objEntry);
  194. // Check and get the new item..
  195. objNewEntry = UpdateCache (strKey, objEntry, true, CacheItemRemovedReason.Removed);
  196. if (objNewEntry == null)
  197. return null;
  198. return objEntry.Item;
  199. }
  200. /// <summary>
  201. /// Inserts an item into the Cache object with a cache key to
  202. /// reference its location and using default values provided by
  203. /// the CacheItemPriority enumeration.
  204. /// </summary>
  205. /// <param name="strKey">The cache key used to reference the item.</param>
  206. /// <param name="objItem">The item to be added to the cache.</param>
  207. public void Insert (string strKey, object objItem)
  208. {
  209. Add (strKey,
  210. objItem,
  211. null,
  212. NoAbsoluteExpiration,
  213. NoSlidingExpiration,
  214. CacheItemPriority.Default,
  215. null);
  216. }
  217. /// <summary>
  218. /// Inserts an object into the Cache that has file or key dependencies.
  219. /// </summary>
  220. /// <param name="strKey">The cache key used to reference the item.</param>
  221. /// <param name="objItem">The item to be added to the cache.</param>
  222. /// <param name="objDependency">
  223. /// The file or cache key dependencies for the item. When any
  224. /// dependency changes, the object becomes invalid and is removed
  225. /// from the cache. If there are no dependencies, this paramter
  226. /// contains a null reference.
  227. /// </param>
  228. public void Insert (string strKey, object objItem, CacheDependency objDependency)
  229. {
  230. Add (strKey,
  231. objItem,
  232. objDependency,
  233. NoAbsoluteExpiration,
  234. NoSlidingExpiration,
  235. CacheItemPriority.Default,
  236. null);
  237. }
  238. /// <summary>
  239. /// Inserts an object into the Cache with dependencies and expiration policies.
  240. /// </summary>
  241. /// <param name="strKey">The cache key used to reference the item.</param>
  242. /// <param name="objItem">The item to be added to the cache.</param>
  243. /// <param name="objDependency">
  244. /// The file or cache key dependencies for the item. When any
  245. /// dependency changes, the object becomes invalid and is removed
  246. /// from the cache. If there are no dependencies, this paramter
  247. /// contains a null reference.
  248. /// </param>
  249. /// <param name="absolutExpiration">
  250. /// The time at which the added object expires and is removed from the cache.
  251. /// </param>
  252. /// <param name="slidingExpiration">The interval between the
  253. /// time the added object was last accessed and when that object
  254. /// expires. If this value is the equivalent of 20 minutes, the
  255. /// object expires and is removed from the cache 20 minutes after
  256. /// it is last accessed.
  257. /// </param>
  258. public void Insert (string strKey,
  259. object objItem,
  260. CacheDependency objDependency,
  261. DateTime absolutExpiration,
  262. TimeSpan slidingExpiration)
  263. {
  264. Add (strKey,
  265. objItem,
  266. objDependency,
  267. absolutExpiration,
  268. slidingExpiration,
  269. CacheItemPriority.Default,
  270. null);
  271. }
  272. /// <summary>
  273. /// Inserts an object into the Cache object with dependencies,
  274. /// expiration and priority policies, and a delegate you can use
  275. /// to notify your application when the inserted item is removed
  276. /// from the Cache.
  277. /// </summary>
  278. /// <param name="strKey">The cache key used to reference the item.</param>
  279. /// <param name="objItem">The item to be added to the cache.</param>
  280. /// <param name="objDependency">
  281. /// The file or cache key dependencies for the item. When any
  282. /// dependency changes, the object becomes invalid and is removed
  283. /// from the cache. If there are no dependencies, this paramter
  284. /// contains a null reference.
  285. /// </param>
  286. /// <param name="absolutExpiration">
  287. /// The time at which the added object expires and is removed from the cache.
  288. /// </param>
  289. /// <param name="slidingExpiration">
  290. /// The interval between the time the added object was last
  291. /// accessed and when that object expires. If this value is the
  292. /// equivalent of 20 minutes, the object expires and is removed
  293. /// from the cache 20 minutes after it is last accessed.
  294. /// </param>
  295. /// <param name="enumPriority">The relative cost of the object,
  296. /// as expressed by the CacheItemPriority enumeration. The cache
  297. /// uses this value when it evicts objects; objects with a lower
  298. /// cost are removed from the cache before objects with a higher
  299. /// cost.
  300. /// </param>
  301. /// <param name="eventRemoveCallback">A delegate that, if
  302. /// provided, is called when an object is removed from the cache.
  303. /// You can use this to notify applications when their objects
  304. /// are deleted from the cache.
  305. /// </param>
  306. public void Insert (string strKey,
  307. object objItem,
  308. CacheDependency objDependency,
  309. DateTime absolutExpiration,
  310. TimeSpan slidingExpiration,
  311. CacheItemPriority enumPriority,
  312. CacheItemRemovedCallback eventRemoveCallback)
  313. {
  314. Add (strKey,
  315. objItem,
  316. objDependency,
  317. absolutExpiration,
  318. slidingExpiration,
  319. enumPriority,
  320. eventRemoveCallback);
  321. }
  322. internal void InsertPrivate (string strKey,
  323. object objItem,
  324. CacheDependency objDependency,
  325. DateTime absolutExpiration,
  326. TimeSpan slidingExpiration,
  327. CacheItemPriority enumPriority,
  328. CacheItemRemovedCallback eventRemoveCallback)
  329. {
  330. Add (strKey,
  331. objItem,
  332. objDependency,
  333. absolutExpiration,
  334. slidingExpiration,
  335. enumPriority,
  336. eventRemoveCallback, false);
  337. }
  338. /// <summary>
  339. /// Removes the specified item from the Cache object.
  340. /// </summary>
  341. /// <param name="strKey">The cache key for the cache item to remove.</param>
  342. /// <returns>
  343. /// The item removed from the Cache. If the value in the key
  344. /// parameter is not found, returns a null reference.
  345. /// </returns>
  346. public object Remove (string strKey)
  347. {
  348. return Remove (strKey, CacheItemRemovedReason.Removed);
  349. }
  350. /// <summary>
  351. /// Internal method that updates the cache, decremenents the
  352. /// number of existing items and call close on the cache entry.
  353. /// This method is also used from the ExpiresBuckets class to
  354. /// remove an item during GC flush.
  355. /// </summary>
  356. /// <param name="strKey">The cache key for the cache item to remove.</param>
  357. /// <param name="enumReason">Reason why the item is removed.</param>
  358. /// <returns>
  359. /// The item removed from the Cache. If the value in the key
  360. /// parameter is not found, returns a null reference.
  361. /// </returns>
  362. internal object Remove (string strKey, CacheItemRemovedReason enumReason)
  363. {
  364. CacheEntry objEntry = UpdateCache (strKey, null, true, enumReason);
  365. if (objEntry == null)
  366. return null;
  367. Interlocked.Decrement (ref _nItems);
  368. // Close the cache entry (calls the remove delegate)
  369. objEntry.Close (enumReason);
  370. return objEntry.Item;
  371. }
  372. /// <summary>
  373. /// Retrieves the specified item from the Cache object.
  374. /// </summary>
  375. /// <param name="strKey">The identifier for the cache item to retrieve.</param>
  376. /// <returns>The retrieved cache item, or a null reference.</returns>
  377. public object Get (string strKey)
  378. {
  379. CacheEntry objEntry = UpdateCache (strKey, null, false, CacheItemRemovedReason.Expired);
  380. if (objEntry == null)
  381. return null;
  382. return objEntry.Item;
  383. }
  384. internal CacheEntry GetEntry (string strKey)
  385. {
  386. CacheEntry objEntry = UpdateCache (strKey, null, false, CacheItemRemovedReason.Expired);
  387. if (objEntry == null)
  388. return null;
  389. return objEntry;
  390. }
  391. /// <summary>
  392. /// Internal method used for removing, updating and adding CacheEntries into the cache.
  393. /// </summary>
  394. /// <param name="strKey">The identifier for the cache item to modify</param>
  395. /// <param name="objEntry">
  396. /// CacheEntry to use for overwrite operation, if this
  397. /// parameter is null and overwrite true the item is going to be
  398. /// removed
  399. /// </param>
  400. /// <param name="boolOverwrite">
  401. /// If true the objEntry parameter is used to overwrite the
  402. /// strKey entry
  403. /// </param>
  404. /// <param name="enumReason">Reason why an item was removed</param>
  405. /// <returns></returns>
  406. private CacheEntry UpdateCache (string strKey,
  407. CacheEntry objEntry,
  408. bool boolOverwrite,
  409. CacheItemRemovedReason enumReason)
  410. {
  411. if (strKey == null)
  412. throw new ArgumentNullException ("strKey");
  413. long ticksNow = DateTime.Now.Ticks;
  414. long ticksExpires = long.MaxValue;
  415. bool boolGetItem = false;
  416. bool boolExpiried = false;
  417. bool boolWrite = false;
  418. bool boolRemoved = false;
  419. // Are we getting the item from the hashtable
  420. if (boolOverwrite == false && strKey.Length > 0 && objEntry == null)
  421. boolGetItem = true;
  422. // TODO: Optimize this method, move out functionality outside the lock
  423. _lockEntries.AcquireReaderLock (-1);
  424. try {
  425. if (boolGetItem) {
  426. objEntry = (CacheEntry) _arrEntries [strKey];
  427. if (objEntry == null)
  428. return null;
  429. }
  430. if (objEntry != null) {
  431. // Check if we have expired
  432. if (objEntry.HasSlidingExpiration || objEntry.HasAbsoluteExpiration) {
  433. if (objEntry.Expires < ticksNow) {
  434. // We have expired, remove the item from the cache
  435. boolWrite = true;
  436. boolExpiried = true;
  437. }
  438. }
  439. }
  440. // Check if we going to modify the hashtable
  441. if (boolWrite || (boolOverwrite && !boolExpiried)) {
  442. // Upgrade our lock to write
  443. Threading.LockCookie objCookie = _lockEntries.UpgradeToWriterLock (-1);
  444. try {
  445. // Check if we going to just modify an existing entry (or add)
  446. if (boolOverwrite && objEntry != null) {
  447. _arrEntries [strKey] = objEntry;
  448. } else {
  449. // We need to remove the item, fetch the item first
  450. objEntry = (CacheEntry) _arrEntries [strKey];
  451. if (objEntry != null)
  452. _arrEntries.Remove (strKey);
  453. boolRemoved = true;
  454. }
  455. } finally {
  456. _lockEntries.DowngradeFromWriterLock (ref objCookie);
  457. }
  458. }
  459. // If the entry haven't expired or been removed update the info
  460. if (!boolExpiried && !boolRemoved) {
  461. // Update that we got a hit
  462. objEntry.Hits++;
  463. if (objEntry.HasSlidingExpiration)
  464. ticksExpires = ticksNow + objEntry.SlidingExpiration;
  465. }
  466. } finally {
  467. _lockEntries.ReleaseLock ();
  468. }
  469. // If the item was removed we need to remove it from the CacheExpired class also
  470. if (boolRemoved) {
  471. if (objEntry != null) {
  472. if (objEntry.HasAbsoluteExpiration || objEntry.HasSlidingExpiration)
  473. _objExpires.Remove (objEntry);
  474. objEntry.Close (enumReason);
  475. }
  476. return null;
  477. }
  478. // If we have sliding expiration and we have a correct hit, update the expiration manager
  479. if (objEntry.HasSlidingExpiration) {
  480. _objExpires.Update (objEntry, ticksExpires);
  481. objEntry.Expires = ticksExpires;
  482. }
  483. // Return the cache entry
  484. return objEntry;
  485. }
  486. /// <summary>
  487. /// Gets the number of items stored in the cache.
  488. /// </summary>
  489. public int Count {
  490. get { return _nItems; }
  491. }
  492. /// <summary>
  493. /// Gets or sets the cache item at the specified key.
  494. /// </summary>
  495. public object this [string strKey] {
  496. get {
  497. return Get (strKey);
  498. }
  499. set {
  500. Insert (strKey, value);
  501. }
  502. }
  503. }
  504. }