Cache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. ret.Disabled = true;
  127. cache.Remove (key);
  128. return ret;
  129. }
  130. public object Add (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  131. {
  132. if (key == null)
  133. throw new ArgumentNullException ("key");
  134. bool locked = false;
  135. try {
  136. cacheLock.EnterWriteLock ();
  137. locked = true;
  138. CacheItem it = GetCacheItem (key);
  139. if (it != null)
  140. return it.Value;
  141. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, false);
  142. } finally {
  143. if (locked)
  144. cacheLock.ExitWriteLock ();
  145. }
  146. return null;
  147. }
  148. public object Get (string key)
  149. {
  150. bool locked = false;
  151. try {
  152. cacheLock.EnterUpgradeableReadLock ();
  153. locked = true;
  154. CacheItem it = GetCacheItem (key);
  155. if (it == null)
  156. return null;
  157. if (it.Dependency != null && it.Dependency.HasChanged) {
  158. try {
  159. cacheLock.EnterWriteLock ();
  160. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false);
  161. } finally {
  162. cacheLock.ExitWriteLock ();
  163. }
  164. return null;
  165. }
  166. if (!DisableExpiration) {
  167. if (it.SlidingExpiration != NoSlidingExpiration) {
  168. it.AbsoluteExpiration = DateTime.Now + it.SlidingExpiration;
  169. // Cast to long is ok since we know that sliding expiration
  170. // is less than 365 days (31536000000ms)
  171. long remaining = (long)it.SlidingExpiration.TotalMilliseconds;
  172. it.ExpiresAt = it.AbsoluteExpiration.Ticks;
  173. if (expirationTimer != null && (expirationTimerPeriod == 0 || expirationTimerPeriod > remaining)) {
  174. expirationTimerPeriod = remaining;
  175. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  176. }
  177. } else if (DateTime.Now >= it.AbsoluteExpiration) {
  178. try {
  179. cacheLock.EnterWriteLock ();
  180. Remove (key, CacheItemRemovedReason.Expired, false);
  181. } finally {
  182. cacheLock.ExitWriteLock ();
  183. }
  184. return null;
  185. }
  186. }
  187. return it.Value;
  188. } finally {
  189. if (locked) {
  190. cacheLock.ExitUpgradeableReadLock ();
  191. }
  192. }
  193. }
  194. public void Insert (string key, object value)
  195. {
  196. Insert (key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
  197. }
  198. public void Insert (string key, object value, CacheDependency dependencies)
  199. {
  200. Insert (key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, true);
  201. }
  202. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
  203. {
  204. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, true);
  205. }
  206. public void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  207. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
  208. {
  209. Insert (key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, onRemoveCallback, true);
  210. }
  211. void Insert (string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
  212. CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback, bool doLock)
  213. {
  214. if (key == null)
  215. throw new ArgumentNullException ("key");
  216. if (value == null)
  217. throw new ArgumentNullException ("value");
  218. if (slidingExpiration < TimeSpan.Zero || slidingExpiration > TimeSpan.FromDays (365))
  219. throw new ArgumentNullException ("slidingExpiration");
  220. if (absoluteExpiration != NoAbsoluteExpiration && slidingExpiration != NoSlidingExpiration)
  221. throw new ArgumentException ("Both absoluteExpiration and slidingExpiration are specified");
  222. CacheItem ci = new CacheItem ();
  223. ci.Value = value;
  224. ci.Key = key;
  225. if (dependencies != null) {
  226. ci.Dependency = dependencies;
  227. dependencies.DependencyChanged += new EventHandler (OnDependencyChanged);
  228. dependencies.SetCache (DependencyCache);
  229. }
  230. ci.Priority = priority;
  231. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, onRemoveCallback, key, doLock);
  232. }
  233. internal void SetItemTimeout (string key, DateTime absoluteExpiration, TimeSpan slidingExpiration, bool doLock)
  234. {
  235. CacheItem ci = null;
  236. bool locked = false;
  237. try {
  238. if (doLock) {
  239. cacheLock.EnterWriteLock ();
  240. locked = true;
  241. }
  242. ci = GetCacheItem (key);
  243. if (ci != null)
  244. SetItemTimeout (ci, absoluteExpiration, slidingExpiration, ci.OnRemoveCallback, null, false);
  245. } finally {
  246. if (locked) {
  247. cacheLock.ExitWriteLock ();
  248. }
  249. }
  250. }
  251. void SetItemTimeout (CacheItem ci, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemRemovedCallback onRemoveCallback,
  252. string key, bool doLock)
  253. {
  254. bool disableExpiration = DisableExpiration;
  255. if (!disableExpiration) {
  256. ci.SlidingExpiration = slidingExpiration;
  257. if (slidingExpiration != NoSlidingExpiration)
  258. ci.AbsoluteExpiration = DateTime.Now + slidingExpiration;
  259. else
  260. ci.AbsoluteExpiration = absoluteExpiration;
  261. }
  262. ci.OnRemoveCallback = onRemoveCallback;
  263. bool locked = false;
  264. try {
  265. if (doLock) {
  266. cacheLock.EnterWriteLock ();
  267. locked = true;
  268. }
  269. if (ci.Timer != null) {
  270. ci.Timer.Dispose ();
  271. ci.Timer = null;
  272. }
  273. if (key != null)
  274. cache [key] = ci;
  275. ci.LastChange = DateTime.Now;
  276. if (!disableExpiration && ci.AbsoluteExpiration != NoAbsoluteExpiration)
  277. EnqueueTimedItem (ci);
  278. } finally {
  279. if (locked) {
  280. cacheLock.ExitWriteLock ();
  281. }
  282. }
  283. }
  284. // MUST be called with cache lock held
  285. void EnqueueTimedItem (CacheItem item)
  286. {
  287. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - DateTime.Now).TotalMilliseconds);
  288. item.ExpiresAt = item.AbsoluteExpiration.Ticks;
  289. if (timedItems == null)
  290. timedItems = new CacheItemPriorityQueue ();
  291. if (remaining > 4294967294)
  292. // Maximum due time for timer
  293. // Item will expire properly anyway, as the timer will be
  294. // rescheduled for the item's expiration time once that item is
  295. // bubbled to the top of the priority queue.
  296. expirationTimerPeriod = 4294967294;
  297. else
  298. expirationTimerPeriod = remaining;
  299. if (expirationTimer == null)
  300. expirationTimer = new Timer (new TimerCallback (ExpireItems), null, expirationTimerPeriod, expirationTimerPeriod);
  301. else if (expirationTimerPeriod > remaining)
  302. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  303. timedItems.Enqueue (item);
  304. }
  305. public object Remove (string key)
  306. {
  307. return Remove (key, CacheItemRemovedReason.Removed, true);
  308. }
  309. object Remove (string key, CacheItemRemovedReason reason, bool doLock)
  310. {
  311. CacheItem it = null;
  312. bool locked = false;
  313. try {
  314. if (doLock) {
  315. cacheLock.EnterWriteLock ();
  316. locked = true;
  317. }
  318. it = RemoveCacheItem (key);
  319. } finally {
  320. if (locked) {
  321. cacheLock.ExitWriteLock ();
  322. }
  323. }
  324. if (it != null) {
  325. Timer t = it.Timer;
  326. if (t != null)
  327. t.Dispose ();
  328. if (it.Dependency != null) {
  329. it.Dependency.SetCache (null);
  330. it.Dependency.DependencyChanged -= new EventHandler (OnDependencyChanged);
  331. it.Dependency.Dispose ();
  332. }
  333. if (it.OnRemoveCallback != null) {
  334. try {
  335. it.OnRemoveCallback (key, it.Value, reason);
  336. } catch {
  337. //TODO: anything to be done here?
  338. }
  339. }
  340. object ret = it.Value;
  341. it.Value = null;
  342. it.Key = null;
  343. it.Dependency = null;
  344. it.OnRemoveCallback = null;
  345. return ret;
  346. } else
  347. return null;
  348. }
  349. // Used when shutting down the application so that
  350. // session_end events are sent for all sessions.
  351. internal void InvokePrivateCallbacks ()
  352. {
  353. CacheItemRemovedReason reason = CacheItemRemovedReason.Removed;
  354. bool locked = false;
  355. try {
  356. cacheLock.EnterReadLock ();
  357. locked = true;
  358. foreach (string key in cache.Keys) {
  359. CacheItem item = GetCacheItem (key);
  360. if (item.Disabled)
  361. continue;
  362. if (item != null && item.OnRemoveCallback != null) {
  363. try {
  364. item.OnRemoveCallback (key, item.Value, reason);
  365. } catch {
  366. //TODO: anything to be done here?
  367. }
  368. }
  369. }
  370. } finally {
  371. if (locked) {
  372. cacheLock.ExitReadLock ();
  373. }
  374. }
  375. }
  376. public IDictionaryEnumerator GetEnumerator ()
  377. {
  378. ArrayList list = new ArrayList ();
  379. bool locked = false;
  380. try {
  381. cacheLock.EnterReadLock ();
  382. locked = true;
  383. foreach (CacheItem it in cache.Values)
  384. list.Add (it);
  385. } finally {
  386. if (locked) {
  387. cacheLock.ExitReadLock ();
  388. }
  389. }
  390. return new CacheItemEnumerator (list);
  391. }
  392. IEnumerator IEnumerable.GetEnumerator ()
  393. {
  394. return GetEnumerator ();
  395. }
  396. void OnDependencyChanged (object o, EventArgs a)
  397. {
  398. CheckDependencies ();
  399. }
  400. void ExpireItems (object data)
  401. {
  402. DateTime now = DateTime.Now;
  403. CacheItem item = timedItems.Peek ();
  404. while (item != null) {
  405. if (!item.Disabled && item.ExpiresAt > now.Ticks)
  406. break;
  407. if (item.Disabled)
  408. continue;
  409. item = timedItems.Dequeue ();
  410. Remove (item.Key, CacheItemRemovedReason.Expired, true);
  411. item = timedItems.Peek ();
  412. }
  413. if (item != null) {
  414. long remaining = Math.Max (0, (long)(item.AbsoluteExpiration - now).TotalMilliseconds);
  415. if (expirationTimerPeriod > remaining) {
  416. expirationTimerPeriod = remaining;
  417. expirationTimer.Change (expirationTimerPeriod, expirationTimerPeriod);
  418. }
  419. return;
  420. }
  421. expirationTimer.Change (Timeout.Infinite, Timeout.Infinite);
  422. expirationTimerPeriod = 0;
  423. }
  424. void ItemExpired(object cacheItem) {
  425. CacheItem ci = (CacheItem)cacheItem;
  426. ci.Timer.Dispose();
  427. ci.Timer = null;
  428. Remove (ci.Key, CacheItemRemovedReason.Expired, true);
  429. }
  430. internal void CheckDependencies ()
  431. {
  432. IList list;
  433. bool locked = false;
  434. try {
  435. cacheLock.EnterWriteLock ();
  436. locked = true;
  437. list = new List <CacheItem> ();
  438. foreach (CacheItem it in cache.Values)
  439. list.Add (it);
  440. foreach (CacheItem it in list) {
  441. if (it.Dependency != null && it.Dependency.HasChanged)
  442. Remove (it.Key, CacheItemRemovedReason.DependencyChanged, false);
  443. }
  444. } finally {
  445. if (locked) {
  446. cacheLock.ExitWriteLock ();
  447. }
  448. }
  449. }
  450. internal DateTime GetKeyLastChange (string key)
  451. {
  452. bool locked = false;
  453. try {
  454. cacheLock.EnterReadLock ();
  455. locked = true;
  456. CacheItem it = GetCacheItem (key);
  457. if (it == null)
  458. return DateTime.MaxValue;
  459. return it.LastChange;
  460. } finally {
  461. if (locked) {
  462. cacheLock.ExitReadLock ();
  463. }
  464. }
  465. }
  466. internal Cache DependencyCache {
  467. get {
  468. if (dependencyCache == null)
  469. return this;
  470. return dependencyCache;
  471. }
  472. set { dependencyCache = value; }
  473. }
  474. }
  475. }