-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
MemoryCache.cs
906 lines (820 loc) · 32.6 KB
/
MemoryCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Caching.Configuration;
using System.Runtime.Caching.Resources;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
namespace System.Runtime.Caching
{
public class MemoryCache : ObjectCache, IEnumerable, IDisposable
{
private const DefaultCacheCapabilities CAPABILITIES = DefaultCacheCapabilities.InMemoryProvider
| DefaultCacheCapabilities.CacheEntryChangeMonitors
| DefaultCacheCapabilities.AbsoluteExpirations
| DefaultCacheCapabilities.SlidingExpirations
| DefaultCacheCapabilities.CacheEntryUpdateCallback
| DefaultCacheCapabilities.CacheEntryRemovedCallback;
private static readonly TimeSpan s_oneYear = new TimeSpan(365, 0, 0, 0);
private static readonly object s_initLock = new object();
private static MemoryCache s_defaultCache;
private static readonly CacheEntryRemovedCallback s_sentinelRemovedCallback = new CacheEntryRemovedCallback(SentinelEntry.OnCacheEntryRemovedCallback);
private GCHandleRef<MemoryCacheStore>[] _storeRefs;
private int _storeCount;
private int _disposed;
private MemoryCacheStatistics _stats;
private readonly string _name;
private Counters _perfCounters;
private readonly bool _configLess;
private bool _useMemoryCacheManager = true;
private bool _throwOnDisposed;
private EventHandler _onAppDomainUnload;
private UnhandledExceptionEventHandler _onUnhandledException;
#if NET
[UnsupportedOSPlatformGuard("browser")]
private static bool _countersSupported => !OperatingSystem.IsBrowser();
#else
private static bool _countersSupported => true;
#endif
private bool IsDisposed { get { return (_disposed == 1); } }
internal bool ConfigLess { get { return _configLess; } }
private sealed class SentinelEntry
{
private readonly string _key;
private readonly ChangeMonitor _expensiveObjectDependency;
private readonly CacheEntryUpdateCallback _updateCallback;
internal SentinelEntry(string key, ChangeMonitor expensiveObjectDependency, CacheEntryUpdateCallback callback)
{
_key = key;
_expensiveObjectDependency = expensiveObjectDependency;
_updateCallback = callback;
}
internal string Key
{
get { return _key; }
}
internal ChangeMonitor ExpensiveObjectDependency
{
get { return _expensiveObjectDependency; }
}
internal CacheEntryUpdateCallback CacheEntryUpdateCallback
{
get { return _updateCallback; }
}
private static bool IsPolicyValid(CacheItemPolicy policy)
{
if (policy == null)
{
return false;
}
// see if any change monitors have changed
bool hasChanged = false;
Collection<ChangeMonitor> changeMonitors = policy.ChangeMonitors;
if (changeMonitors != null)
{
foreach (ChangeMonitor monitor in changeMonitors)
{
if (monitor != null && monitor.HasChanged)
{
hasChanged = true;
break;
}
}
}
// if the monitors haven't changed yet and we have an update callback
// then the policy is valid
if (!hasChanged && policy.UpdateCallback != null)
{
return true;
}
// if the monitors have changed we need to dispose them
if (hasChanged)
{
foreach (ChangeMonitor monitor in changeMonitors)
{
monitor?.Dispose();
}
}
return false;
}
internal static void OnCacheEntryRemovedCallback(CacheEntryRemovedArguments arguments)
{
MemoryCache cache = arguments.Source as MemoryCache;
SentinelEntry entry = arguments.CacheItem.Value as SentinelEntry;
CacheEntryRemovedReason reason = arguments.RemovedReason;
switch (reason)
{
case CacheEntryRemovedReason.Expired:
break;
case CacheEntryRemovedReason.ChangeMonitorChanged:
if (entry.ExpensiveObjectDependency.HasChanged)
{
// If the expensiveObject has been removed explicitly by Cache.Remove,
// return from the SentinelEntry removed callback
// thus effectively removing the SentinelEntry from the cache.
return;
}
break;
case CacheEntryRemovedReason.Evicted:
Debug.Fail("Reason should never be CacheEntryRemovedReason.Evicted since the entry was inserted as NotRemovable.");
return;
default:
// do nothing if reason is Removed or CacheSpecificEviction
return;
}
// invoke update callback
try
{
CacheEntryUpdateArguments args = new CacheEntryUpdateArguments(cache, reason, entry.Key, null);
entry.CacheEntryUpdateCallback(args);
object expensiveObject = args.UpdatedCacheItem?.Value;
CacheItemPolicy policy = args.UpdatedCacheItemPolicy;
// Only update the "expensive" object if the user returns a new object,
// a policy with update callback, and the change monitors haven't changed. (Inserting
// with change monitors that have already changed will cause recursion.)
if (expensiveObject != null && IsPolicyValid(policy))
{
cache.Set(entry.Key, expensiveObject, policy);
}
else
{
cache.Remove(entry.Key);
}
}
catch
{
cache.Remove(entry.Key);
// Review: What should we do with this exception?
}
}
}
// private and internal
internal MemoryCacheStore GetStore(MemoryCacheKey cacheKey)
{
int hashCode = cacheKey.Hash;
if (hashCode < 0)
{
hashCode = (hashCode == int.MinValue) ? 0 : -hashCode;
}
int idx = hashCode % _storeCount;
return _storeRefs[idx].Target;
}
internal object[] AllSRefTargets
{
get
{
var allStores = new MemoryCacheStore[_storeCount];
for (int i = 0; i < _storeCount; i++)
{
allStores[i] = _storeRefs[i].Target;
}
return allStores;
}
}
private void InitDisposableMembers(NameValueCollection config)
{
bool dispose = true;
try
{
try
{
if (_countersSupported)
{
_perfCounters = new Counters(_name);
}
}
catch
{
// ignore exceptions from perf counters
}
for (int i = 0; i < _storeCount; i++)
{
_storeRefs[i] = new GCHandleRef<MemoryCacheStore>(new MemoryCacheStore(this, _perfCounters));
}
_stats = new MemoryCacheStatistics(this, config);
AppDomain appDomain = Thread.GetDomain();
EventHandler onAppDomainUnload = new EventHandler(OnAppDomainUnload);
appDomain.DomainUnload += onAppDomainUnload;
_onAppDomainUnload = onAppDomainUnload;
UnhandledExceptionEventHandler onUnhandledException = new UnhandledExceptionEventHandler(OnUnhandledException);
appDomain.UnhandledException += onUnhandledException;
_onUnhandledException = onUnhandledException;
dispose = false;
}
finally
{
if (dispose)
{
Dispose();
}
}
}
private void OnAppDomainUnload(object unusedObject, EventArgs unusedEventArgs)
{
Dispose();
}
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs eventArgs)
{
// if the CLR is terminating, dispose the cache.
// This will dispose the perf counters
if (eventArgs.IsTerminating)
{
Dispose();
}
}
private static void ValidatePolicy(CacheItemPolicy policy)
{
if (policy.AbsoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration
&& policy.SlidingExpiration != ObjectCache.NoSlidingExpiration)
{
throw new ArgumentException(SR.Invalid_expiration_combination, nameof(policy));
}
if (policy.SlidingExpiration < ObjectCache.NoSlidingExpiration || s_oneYear < policy.SlidingExpiration)
{
throw new ArgumentOutOfRangeException(nameof(policy), RH.Format(SR.Argument_out_of_range, "SlidingExpiration", ObjectCache.NoSlidingExpiration, s_oneYear));
}
if (policy.RemovedCallback != null
&& policy.UpdateCallback != null)
{
throw new ArgumentException(SR.Invalid_callback_combination, nameof(policy));
}
if (policy.Priority != CacheItemPriority.Default && policy.Priority != CacheItemPriority.NotRemovable)
{
throw new ArgumentOutOfRangeException(nameof(policy), RH.Format(SR.Argument_out_of_range, "Priority", CacheItemPriority.Default, CacheItemPriority.NotRemovable));
}
}
// public
// Amount of memory that can be used before
// the cache begins to forcibly remove items.
public long CacheMemoryLimit
{
get
{
return _stats.CacheMemoryLimit;
}
}
public static MemoryCache Default
{
get
{
if (s_defaultCache == null)
{
lock (s_initLock)
{
s_defaultCache ??= new MemoryCache();
}
}
return s_defaultCache;
}
}
public override DefaultCacheCapabilities DefaultCacheCapabilities
{
get
{
return CAPABILITIES;
}
}
public override string Name
{
get { return _name; }
}
internal bool UseMemoryCacheManager
{
get { return _useMemoryCacheManager; }
}
// Percentage of physical memory that can be used before
// the cache begins to forcibly remove items.
public long PhysicalMemoryLimit
{
get
{
return _stats.PhysicalMemoryLimit;
}
}
// The maximum interval of time after which the cache
// will update its memory statistics.
public TimeSpan PollingInterval
{
get
{
return _stats.PollingInterval;
}
}
// Only used for Default MemoryCache
private MemoryCache()
{
_name = "Default";
Init(null);
}
public MemoryCache(string name, NameValueCollection config = null)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Empty_string_invalid, nameof(name));
}
if (string.Equals(name, "default", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(SR.Default_is_reserved, nameof(name));
}
_name = name;
Init(config);
}
// ignoreConfigSection is used when redirecting ASP.NET cache into the MemoryCache. This avoids infinite recursion
// due to the fact that the (ASP.NET) config system uses the cache, and the cache uses the config system.
public MemoryCache(string name, NameValueCollection config, bool ignoreConfigSection)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.Empty_string_invalid, nameof(name));
}
if (string.Equals(name, "default", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(SR.Default_is_reserved, nameof(name));
}
_name = name;
_configLess = ignoreConfigSection;
Init(config);
}
private void Init(NameValueCollection config)
{
_storeCount = Environment.ProcessorCount;
_storeRefs = new GCHandleRef<MemoryCacheStore>[_storeCount];
if (config != null)
{
_useMemoryCacheManager = ConfigUtil.GetBooleanValue(config, ConfigUtil.UseMemoryCacheManager, true);
_throwOnDisposed = ConfigUtil.GetBooleanValue(config, ConfigUtil.ThrowOnDisposed, false);
}
InitDisposableMembers(config);
}
private object AddOrGetExistingInternal(string key, object value, CacheItemPolicy policy)
{
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration;
TimeSpan slidingExp = ObjectCache.NoSlidingExpiration;
CacheItemPriority priority = CacheItemPriority.Default;
Collection<ChangeMonitor> changeMonitors = null;
CacheEntryRemovedCallback removedCallback = null;
if (policy != null)
{
ValidatePolicy(policy);
if (policy.UpdateCallback != null)
{
throw new ArgumentException(SR.Update_callback_must_be_null, nameof(policy));
}
absExp = policy.AbsoluteExpiration;
slidingExp = policy.SlidingExpiration;
priority = policy.Priority;
changeMonitors = policy.ChangeMonitors;
removedCallback = policy.RemovedCallback;
}
if (IsDisposed)
{
if (changeMonitors != null)
{
foreach (ChangeMonitor monitor in changeMonitors)
{
monitor?.Dispose();
}
}
IsDisposedOrThrow();
return null;
}
MemoryCacheKey cacheKey = new MemoryCacheKey(key);
MemoryCacheStore store = GetStore(cacheKey);
MemoryCacheEntry entry = store.AddOrGetExisting(cacheKey, new MemoryCacheEntry(key, value, absExp, slidingExp, priority, changeMonitors, removedCallback, this));
return entry?.Value;
}
public override CacheEntryChangeMonitor CreateCacheEntryChangeMonitor(IEnumerable<string> keys, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
List<string> keysClone = new List<string>(keys);
if (keysClone.Count == 0)
{
throw new ArgumentException(RH.Format(SR.Empty_collection, nameof(keys)));
}
foreach (string key in keysClone)
{
if (key == null)
{
throw new ArgumentException(RH.Format(SR.Collection_contains_null_element, nameof(keys)));
}
}
return new MemoryCacheEntryChangeMonitor(keysClone.AsReadOnly(), regionName, this);
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
// unhook domain events
DisposeSafeCritical();
// stats must be disposed prior to disposing the stores.
_stats?.Dispose();
if (_storeRefs != null)
{
foreach (var storeRef in _storeRefs)
{
storeRef?.Dispose();
}
}
if (_perfCounters != null)
{
if (_countersSupported)
{
_perfCounters.Dispose();
}
}
GC.SuppressFinalize(this);
}
}
private void DisposeSafeCritical()
{
AppDomain appDomain = Thread.GetDomain();
if (_onAppDomainUnload != null)
{
appDomain.DomainUnload -= _onAppDomainUnload;
}
if (_onUnhandledException != null)
{
appDomain.UnhandledException -= _onUnhandledException;
}
}
private object GetInternal(string key, string regionName)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
MemoryCacheEntry entry = GetEntry(key);
return entry?.Value;
}
internal MemoryCacheEntry GetEntry(string key)
{
if (IsDisposedOrThrow())
{
return null;
}
MemoryCacheKey cacheKey = new MemoryCacheKey(key);
MemoryCacheStore store = GetStore(cacheKey);
return store.Get(cacheKey);
}
IEnumerator IEnumerable.GetEnumerator()
{
Hashtable h = new Hashtable();
if (!IsDisposedOrThrow())
{
foreach (var storeRef in _storeRefs)
{
storeRef.Target.CopyTo(h);
}
}
return h.GetEnumerator();
}
protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
Dictionary<string, object> h = new Dictionary<string, object>();
if (!IsDisposedOrThrow())
{
foreach (var storeRef in _storeRefs)
{
storeRef.Target.CopyTo(h);
}
}
return h.GetEnumerator();
}
internal MemoryCacheEntry RemoveEntry(string key, MemoryCacheEntry entry, CacheEntryRemovedReason reason)
{
MemoryCacheKey cacheKey = new MemoryCacheKey(key);
MemoryCacheStore store = GetStore(cacheKey);
return store.Remove(cacheKey, entry, reason);
}
public long Trim(int percent)
{
long trimmed = 0;
if (percent > 100)
{
percent = 100;
}
if (!IsDisposedOrThrow())
{
foreach (var storeRef in _storeRefs)
{
trimmed += storeRef.Target.TrimInternal(percent);
}
}
return trimmed;
}
//Default indexer property
public override object this[string key]
{
get
{
return GetInternal(key, null);
}
set
{
Set(key, value, ObjectCache.InfiniteAbsoluteExpiration);
}
}
//Existence check for a single item
public override bool Contains(string key, string regionName = null)
{
return (GetInternal(key, regionName) != null);
}
public override bool Add(CacheItem item, CacheItemPolicy policy)
{
CacheItem existingEntry = AddOrGetExisting(item, policy);
return (existingEntry == null || existingEntry.Value == null);
}
public override object AddOrGetExisting(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = absoluteExpiration;
return AddOrGetExistingInternal(key, value, policy);
}
public override CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
{
if (item is null)
{
throw new ArgumentNullException(nameof(item));
}
return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy));
}
public override object AddOrGetExisting(string key, object value, CacheItemPolicy policy, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
return AddOrGetExistingInternal(key, value, policy);
}
public override object Get(string key, string regionName = null)
{
return GetInternal(key, regionName);
}
public override CacheItem GetCacheItem(string key, string regionName = null)
{
object value = GetInternal(key, regionName);
return (value != null) ? new CacheItem(key, value) : null;
}
public override void Set(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = absoluteExpiration;
Set(key, value, policy);
}
public override void Set(CacheItem item, CacheItemPolicy policy)
{
if (item is null)
{
throw new ArgumentNullException(nameof(item));
}
Set(item.Key, item.Value, policy);
}
public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration;
TimeSpan slidingExp = ObjectCache.NoSlidingExpiration;
CacheItemPriority priority = CacheItemPriority.Default;
Collection<ChangeMonitor> changeMonitors = null;
CacheEntryRemovedCallback removedCallback = null;
if (policy != null)
{
ValidatePolicy(policy);
if (policy.UpdateCallback != null)
{
Set(key, value, policy.ChangeMonitors, policy.AbsoluteExpiration, policy.SlidingExpiration, policy.UpdateCallback);
return;
}
absExp = policy.AbsoluteExpiration;
slidingExp = policy.SlidingExpiration;
priority = policy.Priority;
changeMonitors = policy.ChangeMonitors;
removedCallback = policy.RemovedCallback;
}
if (IsDisposed)
{
if (changeMonitors != null)
{
foreach (ChangeMonitor monitor in changeMonitors)
{
monitor?.Dispose();
}
}
IsDisposedOrThrow();
return;
}
MemoryCacheKey cacheKey = new MemoryCacheKey(key);
MemoryCacheStore store = GetStore(cacheKey);
store.Set(cacheKey, new MemoryCacheEntry(key, value, absExp, slidingExp, priority, changeMonitors, removedCallback, this));
}
internal void Set(string key,
object value,
Collection<ChangeMonitor> changeMonitors,
DateTimeOffset absoluteExpiration,
TimeSpan slidingExpiration,
CacheEntryUpdateCallback onUpdateCallback)
{
if (key is null)
{
throw new ArgumentNullException(nameof(key));
}
if (changeMonitors == null
&& absoluteExpiration == ObjectCache.InfiniteAbsoluteExpiration
&& slidingExpiration == ObjectCache.NoSlidingExpiration)
{
throw new ArgumentException(SR.Invalid_argument_combination);
}
if (onUpdateCallback == null)
{
throw new ArgumentNullException(nameof(onUpdateCallback));
}
if (IsDisposed)
{
if (changeMonitors != null)
{
foreach (ChangeMonitor monitor in changeMonitors)
{
monitor?.Dispose();
}
}
IsDisposedOrThrow();
return;
}
// Insert updatable cache entry
MemoryCacheKey cacheKey = new MemoryCacheKey(key);
MemoryCacheStore store = GetStore(cacheKey);
MemoryCacheEntry cacheEntry = new MemoryCacheEntry(key,
value,
ObjectCache.InfiniteAbsoluteExpiration,
ObjectCache.NoSlidingExpiration,
CacheItemPriority.NotRemovable,
null,
null,
this);
store.Set(cacheKey, cacheEntry);
// Ensure the sentinel depends on its updatable entry
string[] cacheKeys = { key };
ChangeMonitor expensiveObjectDep = CreateCacheEntryChangeMonitor(cacheKeys);
changeMonitors ??= new Collection<ChangeMonitor>();
changeMonitors.Add(expensiveObjectDep);
// Insert sentinel entry for the updatable cache entry
MemoryCacheKey sentinelCacheKey = new MemoryCacheKey("OnUpdateSentinel" + key);
MemoryCacheStore sentinelStore = GetStore(sentinelCacheKey);
MemoryCacheEntry sentinelCacheEntry = new MemoryCacheEntry(sentinelCacheKey.Key,
new SentinelEntry(key, expensiveObjectDep, onUpdateCallback),
absoluteExpiration,
slidingExpiration,
CacheItemPriority.NotRemovable,
changeMonitors,
s_sentinelRemovedCallback,
this);
sentinelStore.Set(sentinelCacheKey, sentinelCacheEntry);
cacheEntry.ConfigureUpdateSentinel(sentinelStore, sentinelCacheEntry);
}
public override object Remove(string key, string regionName = null)
{
return Remove(key, CacheEntryRemovedReason.Removed, regionName);
}
public object Remove(string key, CacheEntryRemovedReason reason, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (IsDisposedOrThrow())
{
return null;
}
MemoryCacheEntry entry = RemoveEntry(key, null, reason);
return entry?.Value;
}
public override long GetCount(string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
long count = 0;
if (!IsDisposedOrThrow())
{
foreach (var storeRef in _storeRefs)
{
count += storeRef.Target.Count;
}
}
return count;
}
public long GetLastSize(string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
return _stats.GetLastSize();
}
public override IDictionary<string, object> GetValues(IEnumerable<string> keys, string regionName = null)
{
if (regionName != null)
{
throw new NotSupportedException(SR.RegionName_not_supported);
}
if (keys == null)
{
throw new ArgumentNullException(nameof(keys));
}
Dictionary<string, object> values = null;
if (!IsDisposedOrThrow())
{
foreach (string key in keys)
{
if (key == null)
{
throw new ArgumentException(RH.Format(SR.Collection_contains_null_element, nameof(keys)));
}
object value = GetInternal(key, null);
if (value != null)
{
values ??= new Dictionary<string, object>();
values[key] = value;
}
}
}
return values;
}
// used when redirecting ASP.NET cache into the MemoryCache. This avoids infinite recursion
// due to the fact that the (ASP.NET) config system uses the cache, and the cache uses the
// config system.
internal void UpdateConfig(NameValueCollection config)
{
if (config is null)
{
throw new ArgumentNullException(nameof(config));
}
if (!IsDisposed)
{
_stats.UpdateConfig(config);
}
}
private bool IsDisposedOrThrow()
{
if (!IsDisposed)
return false;
if (_throwOnDisposed)
{
string cacheName = $"{this.GetType().FullName}({_name})";
throw new ObjectDisposedException(cacheName);
}
return true;
}
}
}