Cache.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. //
  2. // System.Web.Caching.Cache
  3. //
  4. // Author(s):
  5. // Lluis Sanchez ([email protected])
  6. // Marek Habersack <[email protected]>
  7. //
  8. // (C) 2005-2009 Novell, Inc (http://novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Threading;
  31. using System.Collections;
  32. using System.Collections.Generic;
  33. using System.Linq;
  34. using System.Security.Permissions;
  35. using System.Web.Configuration;
  36. namespace System.Web.Caching
  37. {
  38. // CAS - no InheritanceDemand here as the class is sealed
  39. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. public sealed class Cache: IEnumerable
  41. {
  42. const int LOW_WATER_MARK = 10000; // Target number of items if high water mark is reached
  43. const int HIGH_WATER_MARK = 15000; // We start collection after exceeding this count
  44. public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
  45. public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
  46. // cacheLock will be released in the code below without checking whether it was
  47. // actually acquired. The API doesn't offer a reliable way to check whether the lock
  48. // is being held by the current thread and since Mono does't implement CER
  49. // (Constrained Execution Regions -
  50. // http://msdn.microsoft.com/en-us/library/ms228973.aspx) currently, we have no
  51. // reliable way of recording the information that the lock has been successfully
  52. // acquired.
  53. // It can happen that a Thread.Abort occurs while acquiring the lock and the lock
  54. // isn't actually held. In this case the attempt to release a lock will throw an
  55. // exception. It's better than a race of setting a boolean flag after acquiring the
  56. // lock and then relying upon it here to release it - that may cause a deadlock
  57. // should we fail to release the lock which was successfully acquired but
  58. // Thread.Abort happened right after that during the stloc instruction to set the
  59. // boolean flag. Once CERs are supported we can use the boolean flag reliably.
  60. ReaderWriterLockSlim cacheLock;
  61. CacheItemLRU cache;
  62. CacheItemPriorityQueue timedItems;
  63. Timer expirationTimer;
  64. long expirationTimerPeriod = 0;
  65. Cache dependencyCache;
  66. bool? disableExpiration;
  67. long privateBytesLimit = -1;
  68. long percentagePhysicalMemoryLimit = -1;
  69. bool DisableExpiration {
  70. get {
  71. if (disableExpiration == null) {
  72. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  73. if (cs == null)
  74. disableExpiration = false;
  75. else
  76. disableExpiration = (bool)cs.DisableExpiration;
  77. }
  78. return (bool)disableExpiration;
  79. }
  80. }
  81. public long EffectivePrivateBytesLimit {
  82. get {
  83. if (privateBytesLimit == -1) {
  84. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  85. if (cs == null)
  86. privateBytesLimit = 0;
  87. else
  88. privateBytesLimit = cs.PrivateBytesLimit;
  89. if (privateBytesLimit == 0) {
  90. // http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx
  91. // TODO: calculate
  92. privateBytesLimit = 734003200;
  93. }
  94. }
  95. return privateBytesLimit;
  96. }
  97. }
  98. public long EffectivePercentagePhysicalMemoryLimit {
  99. get {
  100. if (percentagePhysicalMemoryLimit == -1) {
  101. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  102. if (cs == null)
  103. percentagePhysicalMemoryLimit = 0;
  104. else
  105. percentagePhysicalMemoryLimit = cs.PercentagePhysicalMemoryUsedLimit;
  106. if (percentagePhysicalMemoryLimit == 0) {
  107. // http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx
  108. // TODO: calculate
  109. percentagePhysicalMemoryLimit = 97;
  110. }
  111. }
  112. return percentagePhysicalMemoryLimit;
  113. }
  114. }
  115. public Cache ()
  116. {
  117. cacheLock = new ReaderWriterLockSlim ();
  118. cache = new CacheItemLRU (this, HIGH_WATER_MARK, LOW_WATER_MARK);
  119. }
  120. public int Count {
  121. get { return cache.Count; }
  122. }
  123. public object this [string key] {
  124. get { return Get (key); }
  125. set { Insert (key, value); }
  126. }
  127. // Must ALWAYS be called with the cache write lock held
  128. CacheItem RemoveCacheItem (string key)
  129. {
  130. if (key == null)
  131. return null;
  132. CacheItem ret = cache [key];
  133. if (timedItems != null)
  134. timedItems.OnItemDisable (ret);
  135. ret.Disabled = true;
  136. cache.Remove (key);
  137. return ret;
  138. }
  139. public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  140. {
  141. if (key == null)
  142. throw new ArgumentNullException ("key");
  143. try {
  144. cacheLock.EnterWriteLock ();
  145. CacheItem it = cache [key];
  146. if (it != null)
  147. return it.Value;
  148. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, false);
  149. } finally {
  150. // See comment at the top of the file, above cacheLock declaration
  151. cacheLock.ExitWriteLock ();
  152. }
  153. return null;
  154. }
  155. public object Get (string key)
  156. {
  157. try {
  158. cacheLock.EnterUpgradeableReadLock ();
  159. CacheItem it = cache [key];
  160. if (it == null)
  161. return null;
  162. if (it.Dependency != null && it.Dependency.HasChanged) {
  163. try {
  164. cacheLock.EnterWriteLock ();
  165. if (!NeedsUpdate (it, CacheItemUpdateReason.DependencyChanged, false))
  166. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
  167. } finally {
  168. // See comment at the top of the file, above cacheLock declaration
  169. cacheLock.ExitWriteLock ();
  170. }
  171. return null;
  172. }
  173. if (!DisableExpiration) {
  174. if (it.SlidingExpiration != NoSlidingExpiration) {
  175. it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
  176. // Cast to long is ok since we know that sliding expiration
  177. // is less than 365 days (31536000000ms)
  178. long remaining = (long)it.SlidingExpiration.TotalMilliseconds;
  179. it.ExpiresAt = it.AbsoluteExpiration.Ticks;
  180. if (expirationTimer != null && (expirationTimerPeriod == 0 || expirationTimerPeriod > remaining)) {
  181. expirationTimerPeriod = remaining;
  182. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  183. }
  184. } else if (DateTime.Now >= it.AbsoluteExpiration) {
  185. try {
  186. cacheLock.EnterWriteLock ();
  187. if (!NeedsUpdate (it, CacheItemUpdateReason.Expired, false))
  188. Remove (key, CacheItemRemovedReason.Expired, false, true);
  189. } finally {
  190. // See comment at the top of the file, above cacheLock declaration
  191. cacheLock.ExitWriteLock ();
  192. }
  193. return null;
  194. }
  195. }
  196. return it.Value;
  197. } finally {
  198. // See comment at the top of the file, above cacheLock declaration
  199. cacheLock.ExitUpgradeableReadLock ();
  200. }
  201. }
  202. public void Insert (string key, object value)
  203. {
  204. Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, null, true);
  205. }
  206. public void Insert (string key, object value, CacheDependency dependencies)
  207. {
  208. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, null, true);
  209. }
  210. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  211. {
  212. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, null, true);
  213. }
  214. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  215. CacheItemUpdateCallback onUpdateCallback)
  216. {
  217. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, onUpdateCallback, true);
  218. }
  219. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  220. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  221. {
  222. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, true);
  223. }
  224. void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  225. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, CacheItemUpdateCallback onUpdateCallback, bool doLock)
  226. {
  227. if (key == null)
  228. throw new ArgumentNullException ("key");
  229. if (value == null)
  230. throw new ArgumentNullException ("value");
  231. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  232. throw new ArgumentNullException ("slidingExpiration");
  233. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  234. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  235. CacheItem ci = new CacheItem ();
  236. ci.Value = value;
  237. ci.Key = key;
  238. if (dependencies != null) {
  239. ci.Dependency = dependencies;
  240. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  241. dependencies.SetCache (DependencyCache);
  242. }
  243. ci.Priority = priority;
  244. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, onUpdateCallback, key, doLock);
  245. }
  246. internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
  247. {
  248. CacheItem ci = null;
  249. try {
  250. if (doLock)
  251. cacheLock.EnterWriteLock ();
  252. ci = cache [key];
  253. if (ci != null)
  254. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, key, false);
  255. } finally {
  256. if (doLock) {
  257. // See comment at the top of the file, above cacheLock declaration
  258. cacheLock.ExitWriteLock ();
  259. }
  260. }
  261. }
  262. void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback,
  263. CacheItemUpdateCallback onUpdateCallback, string key, bool doLock)
  264. {
  265. bool disableExpiration = DisableExpiration;
  266. if (!disableExpiration) {
  267. ci.SlidingExpiration = slidingExpiration;
  268. if (slidingExpiration != NoSlidingExpiration)
  269. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  270. else
  271. ci.AbsoluteExpiration = absoluteExpiration;
  272. }
  273. ci.OnRemoveCallback = onRemoveCallback;
  274. ci.OnUpdateCallback = onUpdateCallback;
  275. try {
  276. if (doLock)
  277. cacheLock.EnterWriteLock ();
  278. if (key != null) {
  279. cache [key] = ci;
  280. cache.EvictIfNecessary ();
  281. }
  282. ci.LastChange = DateTime.Now;
  283. if (!disableExpiration && ci.AbsoluteExpiration != NoAbsoluteExpiration) {
  284. ci.IsTimedItem = true;
  285. EnqueueTimedItem (ci);
  286. }
  287. } finally {
  288. if (doLock) {
  289. // See comment at the top of the file, above cacheLock declaration
  290. cacheLock.ExitWriteLock ();
  291. }
  292. }
  293. }
  294. // MUST be called with cache lock held
  295. void EnqueueTimedItem (CacheItem item)
  296. {
  297. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  298. item.ExpiresAt = item.AbsoluteExpiration.Ticks;
  299. if (timedItems == null)
  300. timedItems = new CacheItemPriorityQueue ();
  301. if (remaining > 4294967294)
  302. // Maximum due time for timer
  303. // Item will expire properly anyway, as the timer will be
  304. // rescheduled for the item's expiration time once that item is
  305. // bubbled to the top of the priority queue.
  306. expirationTimerPeriod = 4294967294;
  307. else
  308. expirationTimerPeriod = remaining;
  309. if (expirationTimer == null)
  310. expirationTimer = new Timer (new TimerCallback (ExpireItems), null, expirationTimerPeriod, expirationTimerPeriod);
  311. else
  312. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  313. timedItems.Enqueue (item);
  314. }
  315. public object Remove (string key)
  316. {
  317. return Remove (key, CacheItemRemovedReason.Removed, true, true);
  318. }
  319. internal object Remove (string key, CacheItemRemovedReason reason, bool doLock, bool invokeCallback)
  320. {
  321. CacheItem it = null;
  322. try {
  323. if (doLock)
  324. cacheLock.EnterWriteLock ();
  325. it = RemoveCacheItem (key);
  326. } finally {
  327. if (doLock) {
  328. // See comment at the top of the file, above cacheLock declaration
  329. cacheLock.ExitWriteLock ();
  330. }
  331. }
  332. object ret = null;
  333. if (it != null) {
  334. if (it.Dependency != null) {
  335. it.Dependency.SetCache (null);
  336. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  337. it.Dependency.Dispose ();
  338. }
  339. if (invokeCallback && it.OnRemoveCallback != null) {
  340. try {
  341. it.OnRemoveCallback (key, it.Value, reason);
  342. } catch {
  343. //TODO: anything to be done here?
  344. }
  345. }
  346. ret = it.Value;
  347. it.Value = null;
  348. it.Key = null;
  349. it.Dependency = null;
  350. it.OnRemoveCallback = null;
  351. it.OnUpdateCallback = null;
  352. it = null;
  353. }
  354. return ret;
  355. }
  356. // Used when shutting down the application so that
  357. // session_end events are sent for all sessions.
  358. internal void InvokePrivateCallbacks ()
  359. {
  360. try {
  361. cacheLock.EnterReadLock ();
  362. cache.InvokePrivateCallbacks ();
  363. } finally {
  364. // See comment at the top of the file, above cacheLock declaration
  365. cacheLock.ExitReadLock ();
  366. }
  367. }
  368. public IDictionaryEnumerator GetEnumerator ()
  369. {
  370. List <CacheItem> list = null;
  371. try {
  372. cacheLock.EnterReadLock ();
  373. list = cache.ToList ();
  374. } finally {
  375. // See comment at the top of the file, above cacheLock declaration
  376. cacheLock.ExitReadLock ();
  377. }
  378. return new CacheItemEnumerator (list);
  379. }
  380. IEnumerator IEnumerable.GetEnumerator ()
  381. {
  382. return GetEnumerator ();
  383. }
  384. void OnDependencyChanged (object o, EventArgs a)
  385. {
  386. CheckDependencies ();
  387. }
  388. bool NeedsUpdate (CacheItem item, CacheItemUpdateReason reason, bool needLock)
  389. {
  390. try {
  391. if (needLock)
  392. cacheLock.EnterWriteLock ();
  393. if (item == null || item.OnUpdateCallback == null)
  394. return false;
  395. object expensiveObject;
  396. CacheDependency dependency;
  397. DateTime absoluteExpiration;
  398. TimeSpan slidingExpiration;
  399. string key = item.Key;
  400. CacheItemUpdateCallback updateCB = item.OnUpdateCallback;
  401. updateCB (key, reason, out expensiveObject, out dependency, out absoluteExpiration, out slidingExpiration);
  402. if (expensiveObject == null)
  403. return false;
  404. CacheItemPriority priority = item.Priority;
  405. CacheItemRemovedCallback removeCB = item.OnRemoveCallback;
  406. CacheItemRemovedReason whyRemoved;
  407. switch (reason) {
  408. case CacheItemUpdateReason.Expired:
  409. whyRemoved = CacheItemRemovedReason.Expired;
  410. break;
  411. case CacheItemUpdateReason.DependencyChanged:
  412. whyRemoved = CacheItemRemovedReason.DependencyChanged;
  413. break;
  414. default:
  415. whyRemoved = CacheItemRemovedReason.Removed;
  416. break;
  417. }
  418. Remove (key, whyRemoved, false, false);
  419. Insert (key, expensiveObject, dependency, absoluteExpiration, slidingExpiration, priority, removeCB, updateCB, false);
  420. return true;
  421. } catch (Exception) {
  422. return false;
  423. } finally {
  424. if (needLock) {
  425. // See comment at the top of the file, above cacheLock declaration
  426. cacheLock.ExitWriteLock ();
  427. }
  428. }
  429. }
  430. void ExpireItems (object data)
  431. {
  432. DateTime now = DateTime.Now;
  433. CacheItem item = null;
  434. expirationTimer.Change (Timeout.Infinite, Timeout.Infinite);
  435. try {
  436. cacheLock.EnterWriteLock ();
  437. while (true) {
  438. item = timedItems.Peek ();
  439. if (item == null) {
  440. if (timedItems.Count == 0)
  441. break;
  442. timedItems.Dequeue ();
  443. continue;
  444. }
  445. if (!item.Disabled && item.ExpiresAt > now.Ticks)
  446. break;
  447. if (item.Disabled) {
  448. item = timedItems.Dequeue ();
  449. continue;
  450. }
  451. item = timedItems.Dequeue ();
  452. if (item != null)
  453. if (!NeedsUpdate (item, CacheItemUpdateReason.Expired, false))
  454. Remove (item.Key, CacheItemRemovedReason.Expired, false, true);
  455. }
  456. } finally {
  457. // See comment at the top of the file, above cacheLock declaration
  458. cacheLock.ExitWriteLock ();
  459. }
  460. if (item != null) {
  461. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - now).TotalMilliseconds);
  462. if (remaining > 0 && expirationTimerPeriod > remaining)
  463. expirationTimerPeriod = remaining;
  464. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  465. return;
  466. }
  467. expirationTimer.Change (Timeout.Infinite, Timeout.Infinite);
  468. expirationTimerPeriod = 0;
  469. }
  470. internal void CheckDependencies ()
  471. {
  472. try {
  473. cacheLock.EnterWriteLock ();
  474. List <CacheItem> list = cache.SelectItems (it => {
  475. if (it == null)
  476. return false;
  477. if (it.Dependency != null && it.Dependency.HasChanged && !NeedsUpdate (it, CacheItemUpdateReason.DependencyChanged, false))
  478. return true;
  479. return false;
  480. });
  481. foreach (CacheItem it in list)
  482. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
  483. list.Clear ();
  484. list.TrimExcess ();
  485. } finally {
  486. // See comment at the top of the file, above cacheLock declaration
  487. cacheLock.ExitWriteLock ();
  488. }
  489. }
  490. internal DateTime GetKeyLastChange (string key)
  491. {
  492. try {
  493. cacheLock.EnterReadLock ();
  494. CacheItem it = cache [key];
  495. if (it == null)
  496. return DateTime.MaxValue;
  497. return it.LastChange;
  498. } finally {
  499. // See comment at the top of the file, above cacheLock declaration
  500. cacheLock.ExitReadLock ();
  501. }
  502. }
  503. internal Cache DependencyCache {
  504. get {
  505. if (dependencyCache == null)
  506. return this;
  507. return dependencyCache;
  508. }
  509. set { dependencyCache = value; }
  510. }
  511. }
  512. }