Cache.cs 19 KB

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