Cache.cs 17 KB

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