Cache.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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.Security.Permissions;
  34. using System.Web.Configuration;
  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. public static readonly DateTime NoAbsoluteExpiration = DateTime.MaxValue;
  42. public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
  43. // cacheLock will be released in the code below without checking whether it was
  44. // actually acquired. The API doesn't offer a reliable way to check whether the lock
  45. // is being held by the current thread and since Mono does't implement CER
  46. // (Constrained Execution Regions -
  47. // http://msdn.microsoft.com/en-us/library/ms228973.aspx) currently, we have no
  48. // reliable way of recording the information that the lock has been successfully
  49. // acquired.
  50. // It can happen that a Thread.Abort occurs while acquiring the lock and the lock
  51. // isn't actually held. In this case the attempt to release a lock will throw an
  52. // exception. It's better than a race of setting a boolean flag after acquiring the
  53. // lock and then relying upon it here to release it - that may cause a deadlock
  54. // should we fail to release the lock which was successfully acquired but
  55. // Thread.Abort happened right after that during the stloc instruction to set the
  56. // boolean flag. Once CERs are supported we can use the boolean flag reliably.
  57. ReaderWriterLockSlim cacheLock;
  58. Dictionary <string, CacheItem> cache;
  59. CacheItemPriorityQueue timedItems;
  60. Timer expirationTimer;
  61. long expirationTimerPeriod = 0;
  62. Cache dependencyCache;
  63. bool? disableExpiration;
  64. long privateBytesLimit = -1;
  65. long percentagePhysicalMemoryLimit = -1;
  66. bool DisableExpiration {
  67. get {
  68. if (disableExpiration == null) {
  69. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  70. if (cs == null)
  71. disableExpiration = false;
  72. else
  73. disableExpiration = (bool)cs.DisableExpiration;
  74. }
  75. return (bool)disableExpiration;
  76. }
  77. }
  78. public long EffectivePrivateBytesLimit {
  79. get {
  80. if (privateBytesLimit == -1) {
  81. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  82. if (cs == null)
  83. privateBytesLimit = 0;
  84. else
  85. privateBytesLimit = cs.PrivateBytesLimit;
  86. if (privateBytesLimit == 0) {
  87. // http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx
  88. // TODO: calculate
  89. privateBytesLimit = 734003200;
  90. }
  91. }
  92. return privateBytesLimit;
  93. }
  94. }
  95. public long EffectivePercentagePhysicalMemoryLimit {
  96. get {
  97. if (percentagePhysicalMemoryLimit == -1) {
  98. var cs = WebConfigurationManager.GetWebApplicationSection ("system.web/caching/cache") as CacheSection;
  99. if (cs == null)
  100. percentagePhysicalMemoryLimit = 0;
  101. else
  102. percentagePhysicalMemoryLimit = cs.PercentagePhysicalMemoryUsedLimit;
  103. if (percentagePhysicalMemoryLimit == 0) {
  104. // http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx
  105. // TODO: calculate
  106. percentagePhysicalMemoryLimit = 97;
  107. }
  108. }
  109. return percentagePhysicalMemoryLimit;
  110. }
  111. }
  112. public Cache ()
  113. {
  114. cacheLock = new ReaderWriterLockSlim ();
  115. cache = new Dictionary <string, CacheItem> (StringComparer.Ordinal);
  116. }
  117. public int Count {
  118. get { return cache.Count; }
  119. }
  120. public object this [string key] {
  121. get { return Get (key); }
  122. set { Insert (key, value); }
  123. }
  124. CacheItem GetCacheItem (string key)
  125. {
  126. if (key == null)
  127. return null;
  128. CacheItem ret;
  129. if (cache.TryGetValue (key, out ret))
  130. return ret;
  131. return null;
  132. }
  133. CacheItem RemoveCacheItem (string key)
  134. {
  135. if (key == null)
  136. return null;
  137. CacheItem ret = null;
  138. if (!cache.TryGetValue (key, out ret))
  139. return null;
  140. if (timedItems != null)
  141. timedItems.OnItemDisable (ret);
  142. ret.Disabled = true;
  143. cache.Remove (key);
  144. return ret;
  145. }
  146. public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  147. {
  148. if (key == null)
  149. throw new ArgumentNullException ("key");
  150. try {
  151. cacheLock.EnterWriteLock ();
  152. CacheItem it = GetCacheItem (key);
  153. if (it != null)
  154. return it.Value;
  155. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, false);
  156. } finally {
  157. // See comment at the top of the file, above cacheLock declaration
  158. cacheLock.ExitWriteLock ();
  159. }
  160. return null;
  161. }
  162. public object Get (string key)
  163. {
  164. try {
  165. cacheLock.EnterUpgradeableReadLock ();
  166. CacheItem it = GetCacheItem (key);
  167. if (it == null)
  168. return null;
  169. if (it.Dependency != null && it.Dependency.HasChanged) {
  170. try {
  171. cacheLock.EnterWriteLock ();
  172. if (!NeedsUpdate (it, CacheItemUpdateReason.DependencyChanged, false))
  173. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
  174. } finally {
  175. // See comment at the top of the file, above cacheLock declaration
  176. cacheLock.ExitWriteLock ();
  177. }
  178. return null;
  179. }
  180. if (!DisableExpiration) {
  181. if (it.SlidingExpiration != NoSlidingExpiration) {
  182. it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
  183. // Cast to long is ok since we know that sliding expiration
  184. // is less than 365 days (31536000000ms)
  185. long remaining = (long)it.SlidingExpiration.TotalMilliseconds;
  186. it.ExpiresAt = it.AbsoluteExpiration.Ticks;
  187. if (expirationTimer != null && (expirationTimerPeriod == 0 || expirationTimerPeriod > remaining)) {
  188. expirationTimerPeriod = remaining;
  189. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  190. }
  191. } else if (DateTime.Now >= it.AbsoluteExpiration) {
  192. try {
  193. cacheLock.EnterWriteLock ();
  194. if (!NeedsUpdate (it, CacheItemUpdateReason.Expired, false))
  195. Remove (key, CacheItemRemovedReason.Expired, false, true);
  196. } finally {
  197. // See comment at the top of the file, above cacheLock declaration
  198. cacheLock.ExitWriteLock ();
  199. }
  200. return null;
  201. }
  202. }
  203. return it.Value;
  204. } finally {
  205. // See comment at the top of the file, above cacheLock declaration
  206. cacheLock.ExitUpgradeableReadLock ();
  207. }
  208. }
  209. public void Insert (string key, object value)
  210. {
  211. Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, null, true);
  212. }
  213. public void Insert (string key, object value, CacheDependency dependencies)
  214. {
  215. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, null, true);
  216. }
  217. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  218. {
  219. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, null, true);
  220. }
  221. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  222. CacheItemUpdateCallback onUpdateCallback)
  223. {
  224. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, onUpdateCallback, true);
  225. }
  226. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  227. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  228. {
  229. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, true);
  230. }
  231. void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  232. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, CacheItemUpdateCallback onUpdateCallback, bool doLock)
  233. {
  234. if (key == null)
  235. throw new ArgumentNullException ("key");
  236. if (value == null)
  237. throw new ArgumentNullException ("value");
  238. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  239. throw new ArgumentNullException ("slidingExpiration");
  240. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  241. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  242. CacheItem ci = new CacheItem ();
  243. ci.Value = value;
  244. ci.Key = key;
  245. if (dependencies != null) {
  246. ci.Dependency = dependencies;
  247. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  248. dependencies.SetCache (DependencyCache);
  249. }
  250. ci.Priority = priority;
  251. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, onUpdateCallback, key, doLock);
  252. }
  253. internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
  254. {
  255. CacheItem ci = null;
  256. try {
  257. if (doLock)
  258. cacheLock.EnterWriteLock ();
  259. ci = GetCacheItem (key);
  260. if (ci != null)
  261. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, key, false);
  262. } finally {
  263. if (doLock) {
  264. // See comment at the top of the file, above cacheLock declaration
  265. cacheLock.ExitWriteLock ();
  266. }
  267. }
  268. }
  269. void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback,
  270. CacheItemUpdateCallback onUpdateCallback, string key, bool doLock)
  271. {
  272. bool disableExpiration = DisableExpiration;
  273. if (!disableExpiration) {
  274. ci.SlidingExpiration = slidingExpiration;
  275. if (slidingExpiration != NoSlidingExpiration)
  276. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  277. else
  278. ci.AbsoluteExpiration = absoluteExpiration;
  279. }
  280. ci.OnRemoveCallback = onRemoveCallback;
  281. ci.OnUpdateCallback = onUpdateCallback;
  282. try {
  283. if (doLock)
  284. cacheLock.EnterWriteLock ();
  285. if (ci.Timer != null) {
  286. ci.Timer.Dispose ();
  287. ci.Timer = null;
  288. }
  289. if (key != null)
  290. cache [key] = ci;
  291. ci.LastChange = DateTime.Now;
  292. if (!disableExpiration && ci.AbsoluteExpiration != NoAbsoluteExpiration)
  293. EnqueueTimedItem (ci);
  294. } finally {
  295. if (doLock) {
  296. // See comment at the top of the file, above cacheLock declaration
  297. cacheLock.ExitWriteLock ();
  298. }
  299. }
  300. }
  301. // MUST be called with cache lock held
  302. void EnqueueTimedItem (CacheItem item)
  303. {
  304. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  305. item.ExpiresAt = item.AbsoluteExpiration.Ticks;
  306. if (timedItems == null)
  307. timedItems = new CacheItemPriorityQueue ();
  308. if (remaining > 4294967294)
  309. // Maximum due time for timer
  310. // Item will expire properly anyway, as the timer will be
  311. // rescheduled for the item's expiration time once that item is
  312. // bubbled to the top of the priority queue.
  313. expirationTimerPeriod = 4294967294;
  314. else
  315. expirationTimerPeriod = remaining;
  316. if (expirationTimer == null)
  317. expirationTimer = new Timer (new TimerCallback (ExpireItems), null, expirationTimerPeriod, expirationTimerPeriod);
  318. else
  319. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  320. timedItems.Enqueue (item);
  321. }
  322. public object Remove (string key)
  323. {
  324. return Remove (key, CacheItemRemovedReason.Removed, true, true);
  325. }
  326. object Remove (string key, CacheItemRemovedReason reason, bool doLock, bool invokeCallback)
  327. {
  328. CacheItem it = null;
  329. try {
  330. if (doLock)
  331. cacheLock.EnterWriteLock ();
  332. it = RemoveCacheItem (key);
  333. } finally {
  334. if (doLock) {
  335. // See comment at the top of the file, above cacheLock declaration
  336. cacheLock.ExitWriteLock ();
  337. }
  338. }
  339. if (it != null) {
  340. Timer t = it.Timer;
  341. if (t != null)
  342. t.Dispose ();
  343. if (it.Dependency != null) {
  344. it.Dependency.SetCache (null);
  345. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  346. it.Dependency.Dispose ();
  347. }
  348. if (invokeCallback && it.OnRemoveCallback != null) {
  349. try {
  350. it.OnRemoveCallback (key, it.Value, reason);
  351. } catch {
  352. //TODO: anything to be done here?
  353. }
  354. }
  355. object ret = it.Value;
  356. it.Value = null;
  357. it.Key = null;
  358. it.Dependency = null;
  359. it.OnRemoveCallback = null;
  360. it.OnUpdateCallback = null;
  361. return ret;
  362. } else
  363. return null;
  364. }
  365. // Used when shutting down the application so that
  366. // session_end events are sent for all sessions.
  367. internal void InvokePrivateCallbacks ()
  368. {
  369. CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
  370. try {
  371. cacheLock.EnterReadLock ();
  372. foreach (string key in cache.Keys) {
  373. CacheItem item = GetCacheItem (key);
  374. if (item.Disabled)
  375. continue;
  376. if (item != null && item.OnRemoveCallback != null) {
  377. try {
  378. item.OnRemoveCallback (key, item.Value, reason);
  379. } catch {
  380. //TODO: anything to be done here?
  381. }
  382. }
  383. }
  384. } finally {
  385. // See comment at the top of the file, above cacheLock declaration
  386. cacheLock.ExitReadLock ();
  387. }
  388. }
  389. public IDictionaryEnumerator GetEnumerator ()
  390. {
  391. ArrayList list = new ArrayList ();
  392. try {
  393. cacheLock.EnterReadLock ();
  394. foreach (CacheItem it in cache.Values)
  395. list.Add (it);
  396. } finally {
  397. // See comment at the top of the file, above cacheLock declaration
  398. cacheLock.ExitReadLock ();
  399. }
  400. return new CacheItemEnumerator (list);
  401. }
  402. IEnumerator IEnumerable.GetEnumerator ()
  403. {
  404. return GetEnumerator ();
  405. }
  406. void OnDependencyChanged (object o, EventArgs a)
  407. {
  408. CheckDependencies ();
  409. }
  410. bool NeedsUpdate (CacheItem item, CacheItemUpdateReason reason, bool needLock)
  411. {
  412. try {
  413. if (needLock)
  414. cacheLock.EnterWriteLock ();
  415. if (item == null || item.OnUpdateCallback == null)
  416. return false;
  417. object expensiveObject;
  418. CacheDependency dependency;
  419. DateTime absoluteExpiration;
  420. TimeSpan slidingExpiration;
  421. string key = item.Key;
  422. CacheItemUpdateCallback updateCB = item.OnUpdateCallback;
  423. updateCB (key, reason, out expensiveObject, out dependency, out absoluteExpiration, out slidingExpiration);
  424. if (expensiveObject == null)
  425. return false;
  426. CacheItemPriority priority = item.Priority;
  427. CacheItemRemovedCallback removeCB = item.OnRemoveCallback;
  428. CacheItemRemovedReason whyRemoved;
  429. switch (reason) {
  430. case CacheItemUpdateReason.Expired:
  431. whyRemoved = CacheItemRemovedReason.Expired;
  432. break;
  433. case CacheItemUpdateReason.DependencyChanged:
  434. whyRemoved = CacheItemRemovedReason.DependencyChanged;
  435. break;
  436. default:
  437. whyRemoved = CacheItemRemovedReason.Removed;
  438. break;
  439. }
  440. Remove (key, whyRemoved, false, false);
  441. Insert (key, expensiveObject, dependency, absoluteExpiration, slidingExpiration, priority, removeCB, updateCB, false);
  442. return true;
  443. } catch (Exception) {
  444. return false;
  445. } finally {
  446. if (needLock) {
  447. // See comment at the top of the file, above cacheLock declaration
  448. cacheLock.ExitWriteLock ();
  449. }
  450. }
  451. }
  452. void ExpireItems (object data)
  453. {
  454. DateTime now = DateTime.Now;
  455. CacheItem item = timedItems.Peek ();
  456. try {
  457. cacheLock.EnterWriteLock ();
  458. while (item != null) {
  459. if (!item.Disabled && item.ExpiresAt > now.Ticks)
  460. break;
  461. if (item.Disabled) {
  462. item = timedItems.Dequeue ();
  463. continue;
  464. }
  465. item = timedItems.Dequeue ();
  466. if (!NeedsUpdate (item, CacheItemUpdateReason.Expired, false))
  467. Remove (item.Key, CacheItemRemovedReason.Expired, false, true);
  468. item = timedItems.Peek ();
  469. }
  470. } finally {
  471. // See comment at the top of the file, above cacheLock declaration
  472. cacheLock.ExitWriteLock ();
  473. }
  474. if (item != null) {
  475. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - now).TotalMilliseconds);
  476. if (expirationTimerPeriod != remaining && remaining > 0) {
  477. expirationTimerPeriod = remaining;
  478. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  479. }
  480. return;
  481. }
  482. expirationTimer.Change (Timeout.Infinite, Timeout.Infinite);
  483. expirationTimerPeriod = 0;
  484. }
  485. internal void CheckDependencies ()
  486. {
  487. IList list;
  488. try {
  489. cacheLock.EnterWriteLock ();
  490. list = new List <CacheItem> ();
  491. foreach (CacheItem it in cache.Values)
  492. list.Add (it);
  493. foreach (CacheItem it in list) {
  494. if (it.Dependency != null && it.Dependency.HasChanged && !NeedsUpdate (it, CacheItemUpdateReason.DependencyChanged, false))
  495. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false, true);
  496. }
  497. } finally {
  498. // See comment at the top of the file, above cacheLock declaration
  499. cacheLock.ExitWriteLock ();
  500. }
  501. }
  502. internal DateTime GetKeyLastChange (string key)
  503. {
  504. try {
  505. cacheLock.EnterReadLock ();
  506. CacheItem it = GetCacheItem (key);
  507. if (it == null)
  508. return DateTime.MaxValue;
  509. return it.LastChange;
  510. } finally {
  511. // See comment at the top of the file, above cacheLock declaration
  512. cacheLock.ExitReadLock ();
  513. }
  514. }
  515. internal Cache DependencyCache {
  516. get {
  517. if (dependencyCache == null)
  518. return this;
  519. return dependencyCache;
  520. }
  521. set { dependencyCache = value; }
  522. }
  523. }
  524. }