Cache.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 0 provides a non-expiring lock.
  74. _lockEntries.AcquireReaderLock (0);
  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. if (strKey == null)
  159. throw new ArgumentNullException ("strKey");
  160. if (objItem == null)
  161. throw new ArgumentNullException ("objItem");
  162. if (slidingExpiration > _datetimeOneYear)
  163. throw new ArgumentOutOfRangeException ("slidingExpiration");
  164. CacheEntry objEntry;
  165. CacheEntry objNewEntry;
  166. long longHitRange = 10000;
  167. // todo: check decay and make up the minHit range
  168. objEntry = new CacheEntry (this,
  169. strKey,
  170. objItem,
  171. objDependency,
  172. eventRemoveCallback,
  173. absolutExpiration,
  174. slidingExpiration,
  175. longHitRange,
  176. true,
  177. enumPriority);
  178. Interlocked.Increment (ref _nItems);
  179. // If we have any kind of expiration add into the CacheExpires class
  180. if (objEntry.HasSlidingExpiration || objEntry.HasAbsoluteExpiration)
  181. _objExpires.Add (objEntry);
  182. // Check and get the new item..
  183. objNewEntry = UpdateCache (strKey, objEntry, true, CacheItemRemovedReason.Removed);
  184. if (objNewEntry == null)
  185. return null;
  186. return objEntry.Item;
  187. }
  188. /// <summary>
  189. /// Inserts an item into the Cache object with a cache key to
  190. /// reference its location and using default values provided by
  191. /// the CacheItemPriority enumeration.
  192. /// </summary>
  193. /// <param name="strKey">The cache key used to reference the item.</param>
  194. /// <param name="objItem">The item to be added to the cache.</param>
  195. public void Insert (string strKey, object objItem)
  196. {
  197. Add (strKey,
  198. objItem,
  199. null,
  200. NoAbsoluteExpiration,
  201. NoSlidingExpiration,
  202. CacheItemPriority.Default,
  203. null);
  204. }
  205. /// <summary>
  206. /// Inserts an object into the Cache that has file or key dependencies.
  207. /// </summary>
  208. /// <param name="strKey">The cache key used to reference the item.</param>
  209. /// <param name="objItem">The item to be added to the cache.</param>
  210. /// <param name="objDependency">
  211. /// The file or cache key dependencies for the item. When any
  212. /// dependency changes, the object becomes invalid and is removed
  213. /// from the cache. If there are no dependencies, this paramter
  214. /// contains a null reference.
  215. /// </param>
  216. public void Insert (string strKey, object objItem, CacheDependency objDependency)
  217. {
  218. Add (strKey,
  219. objItem,
  220. objDependency,
  221. NoAbsoluteExpiration,
  222. NoSlidingExpiration,
  223. CacheItemPriority.Default,
  224. null);
  225. }
  226. /// <summary>
  227. /// Inserts an object into the Cache with dependencies and expiration policies.
  228. /// </summary>
  229. /// <param name="strKey">The cache key used to reference the item.</param>
  230. /// <param name="objItem">The item to be added to the cache.</param>
  231. /// <param name="objDependency">
  232. /// The file or cache key dependencies for the item. When any
  233. /// dependency changes, the object becomes invalid and is removed
  234. /// from the cache. If there are no dependencies, this paramter
  235. /// contains a null reference.
  236. /// </param>
  237. /// <param name="absolutExpiration">
  238. /// The time at which the added object expires and is removed from the cache.
  239. /// </param>
  240. /// <param name="slidingExpiration">The interval between the
  241. /// time the added object was last accessed and when that object
  242. /// expires. If this value is the equivalent of 20 minutes, the
  243. /// object expires and is removed from the cache 20 minutes after
  244. /// it is last accessed.
  245. /// </param>
  246. public void Insert (string strKey,
  247. object objItem,
  248. CacheDependency objDependency,
  249. DateTime absolutExpiration,
  250. TimeSpan slidingExpiration)
  251. {
  252. Add (strKey,
  253. objItem,
  254. objDependency,
  255. absolutExpiration,
  256. slidingExpiration,
  257. CacheItemPriority.Default,
  258. null);
  259. }
  260. /// <summary>
  261. /// Inserts an object into the Cache object with dependencies,
  262. /// expiration and priority policies, and a delegate you can use
  263. /// to notify your application when the inserted item is removed
  264. /// from the Cache.
  265. /// </summary>
  266. /// <param name="strKey">The cache key used to reference the item.</param>
  267. /// <param name="objItem">The item to be added to the cache.</param>
  268. /// <param name="objDependency">
  269. /// The file or cache key dependencies for the item. When any
  270. /// dependency changes, the object becomes invalid and is removed
  271. /// from the cache. If there are no dependencies, this paramter
  272. /// contains a null reference.
  273. /// </param>
  274. /// <param name="absolutExpiration">
  275. /// The time at which the added object expires and is removed from the cache.
  276. /// </param>
  277. /// <param name="slidingExpiration">
  278. /// The interval between the time the added object was last
  279. /// accessed and when that object expires. If this value is the
  280. /// equivalent of 20 minutes, the object expires and is removed
  281. /// from the cache 20 minutes after it is last accessed.
  282. /// </param>
  283. /// <param name="enumPriority">The relative cost of the object,
  284. /// as expressed by the CacheItemPriority enumeration. The cache
  285. /// uses this value when it evicts objects; objects with a lower
  286. /// cost are removed from the cache before objects with a higher
  287. /// cost.
  288. /// </param>
  289. /// <param name="eventRemoveCallback">A delegate that, if
  290. /// provided, is called when an object is removed from the cache.
  291. /// You can use this to notify applications when their objects
  292. /// are deleted from the cache.
  293. /// </param>
  294. public void Insert (string strKey,
  295. object objItem,
  296. CacheDependency objDependency,
  297. DateTime absolutExpiration,
  298. TimeSpan slidingExpiration,
  299. CacheItemPriority enumPriority,
  300. CacheItemRemovedCallback eventRemoveCallback)
  301. {
  302. Add (strKey,
  303. objItem,
  304. objDependency,
  305. absolutExpiration,
  306. slidingExpiration,
  307. enumPriority,
  308. eventRemoveCallback);
  309. }
  310. /// <summary>
  311. /// Removes the specified item from the Cache object.
  312. /// </summary>
  313. /// <param name="strKey">The cache key for the cache item to remove.</param>
  314. /// <returns>
  315. /// The item removed from the Cache. If the value in the key
  316. /// parameter is not found, returns a null reference.
  317. /// </returns>
  318. public object Remove (string strKey)
  319. {
  320. return Remove (strKey, CacheItemRemovedReason.Removed);
  321. }
  322. /// <summary>
  323. /// Internal method that updates the cache, decremenents the
  324. /// number of existing items and call close on the cache entry.
  325. /// This method is also used from the ExpiresBuckets class to
  326. /// remove an item during GC flush.
  327. /// </summary>
  328. /// <param name="strKey">The cache key for the cache item to remove.</param>
  329. /// <param name="enumReason">Reason why the item is removed.</param>
  330. /// <returns>
  331. /// The item removed from the Cache. If the value in the key
  332. /// parameter is not found, returns a null reference.
  333. /// </returns>
  334. internal object Remove (string strKey, CacheItemRemovedReason enumReason)
  335. {
  336. CacheEntry objEntry = UpdateCache (strKey, null, true, enumReason);
  337. if (objEntry == null)
  338. return null;
  339. Interlocked.Decrement (ref _nItems);
  340. // Close the cache entry (calls the remove delegate)
  341. objEntry.Close (enumReason);
  342. return objEntry.Item;
  343. }
  344. /// <summary>
  345. /// Retrieves the specified item from the Cache object.
  346. /// </summary>
  347. /// <param name="strKey">The identifier for the cache item to retrieve.</param>
  348. /// <returns>The retrieved cache item, or a null reference.</returns>
  349. public object Get (string strKey)
  350. {
  351. CacheEntry objEntry = UpdateCache (strKey, null, false, CacheItemRemovedReason.Expired);
  352. if (objEntry == null)
  353. return null;
  354. return objEntry.Item;
  355. }
  356. /// <summary>
  357. /// Internal method used for removing, updating and adding CacheEntries into the cache.
  358. /// </summary>
  359. /// <param name="strKey">The identifier for the cache item to modify</param>
  360. /// <param name="objEntry">
  361. /// CacheEntry to use for overwrite operation, if this
  362. /// parameter is null and overwrite true the item is going to be
  363. /// removed
  364. /// </param>
  365. /// <param name="boolOverwrite">
  366. /// If true the objEntry parameter is used to overwrite the
  367. /// strKey entry
  368. /// </param>
  369. /// <param name="enumReason">Reason why an item was removed</param>
  370. /// <returns></returns>
  371. private CacheEntry UpdateCache (string strKey,
  372. CacheEntry objEntry,
  373. bool boolOverwrite,
  374. CacheItemRemovedReason enumReason)
  375. {
  376. if (strKey == null)
  377. throw new ArgumentNullException ("strKey");
  378. long ticksNow = DateTime.Now.Ticks;
  379. long ticksExpires = long.MaxValue;
  380. bool boolGetItem = false;
  381. bool boolExpiried = false;
  382. bool boolWrite = false;
  383. bool boolRemoved = false;
  384. // Are we getting the item from the hashtable
  385. if (boolOverwrite == false && strKey.Length > 0 && objEntry == null)
  386. boolGetItem = true;
  387. // TODO: Optimize this method, move out functionality outside the lock
  388. _lockEntries.AcquireReaderLock (0);
  389. try {
  390. if (boolGetItem) {
  391. objEntry = (CacheEntry) _arrEntries [strKey];
  392. if (objEntry == null)
  393. return null;
  394. }
  395. if (objEntry != null) {
  396. // Check if we have expired
  397. if (objEntry.HasSlidingExpiration || objEntry.HasAbsoluteExpiration) {
  398. if (objEntry.Expires < ticksNow) {
  399. // We have expired, remove the item from the cache
  400. boolWrite = true;
  401. boolExpiried = true;
  402. }
  403. }
  404. }
  405. // Check if we going to modify the hashtable
  406. if (boolWrite || (boolOverwrite && !boolExpiried)) {
  407. // Upgrade our lock to write
  408. Threading.LockCookie objCookie = _lockEntries.UpgradeToWriterLock (0);
  409. try {
  410. // Check if we going to just modify an existing entry (or add)
  411. if (boolOverwrite && objEntry != null) {
  412. _arrEntries [strKey] = objEntry;
  413. } else {
  414. // We need to remove the item, fetch the item first
  415. objEntry = (CacheEntry) _arrEntries [strKey];
  416. if (objEntry != null)
  417. _arrEntries.Remove (strKey);
  418. boolRemoved = true;
  419. }
  420. } finally {
  421. _lockEntries.DowngradeFromWriterLock (ref objCookie);
  422. }
  423. }
  424. // If the entry haven't expired or been removed update the info
  425. if (!boolExpiried && !boolRemoved) {
  426. // Update that we got a hit
  427. objEntry.Hits++;
  428. if (objEntry.HasSlidingExpiration)
  429. ticksExpires = ticksNow + objEntry.SlidingExpiration;
  430. }
  431. } finally {
  432. _lockEntries.ReleaseLock ();
  433. }
  434. // If the item was removed we need to remove it from the CacheExpired class also
  435. if (boolRemoved) {
  436. if (objEntry != null) {
  437. if (objEntry.HasAbsoluteExpiration || objEntry.HasSlidingExpiration)
  438. _objExpires.Remove (objEntry);
  439. }
  440. // Return the entry, it's not up to the UpdateCache to call Close on the entry
  441. return objEntry;
  442. }
  443. // If we have sliding expiration and we have a correct hit, update the expiration manager
  444. if (objEntry.HasSlidingExpiration)
  445. _objExpires.Update (objEntry, ticksExpires);
  446. // Return the cache entry
  447. return objEntry;
  448. }
  449. /// <summary>
  450. /// Gets the number of items stored in the cache.
  451. /// </summary>
  452. public int Count {
  453. get { return _nItems; }
  454. }
  455. /// <summary>
  456. /// Gets or sets the cache item at the specified key.
  457. /// </summary>
  458. public object this [string strKey] {
  459. get {
  460. return Get (strKey);
  461. }
  462. set {
  463. Insert (strKey, value);
  464. }
  465. }
  466. }
  467. }