Skip to content

Commit 2b3ec33

Browse files
stephentoubBrent Schmaltz
authored and
Brent Schmaltz
committed
Remove fast-path closures from EventBasedLRUCache (#2170)
1 parent 407a288 commit 2b3ec33

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs

+17-7
Original file line numberDiff line numberDiff line change
@@ -390,10 +390,12 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
390390
cacheItem.ExpirationTime = expirationTime;
391391
if (_maintainLRU)
392392
{
393+
var localCacheItem = cacheItem; // avoid closure when !_maintainLRU
394+
var localThis = this;
393395
AddActionToEventQueue(() =>
394396
{
395-
_doubleLinkedList.Remove(cacheItem);
396-
_doubleLinkedList.AddFirst(cacheItem);
397+
localThis._doubleLinkedList.Remove(localCacheItem);
398+
localThis._doubleLinkedList.AddFirst(localCacheItem);
397399
});
398400
}
399401
}
@@ -416,11 +418,13 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
416418
// add the new node to the _doubleLinkedList if _maintainLRU == true
417419
if (_maintainLRU)
418420
{
421+
var localNewCacheItem = newCacheItem; // avoid closure when !_maintainLRU
422+
var localThis = this;
419423
AddActionToEventQueue(() =>
420424
{
421425
// Add a remove operation in case two threads are trying to add the same value. Only the second remove will succeed in this case.
422-
_doubleLinkedList.Remove(newCacheItem);
423-
_doubleLinkedList.AddFirst(newCacheItem);
426+
localThis._doubleLinkedList.Remove(localNewCacheItem);
427+
localThis._doubleLinkedList.AddFirst(localNewCacheItem);
424428
});
425429
}
426430

@@ -492,10 +496,12 @@ public bool TryGetValue(TKey key, out TValue value)
492496
// make sure node hasn't been removed by a different thread
493497
if (_maintainLRU)
494498
{
499+
var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU
500+
var localThis = this;
495501
AddActionToEventQueue(() =>
496502
{
497-
_doubleLinkedList.Remove(cacheItem);
498-
_doubleLinkedList.AddFirst(cacheItem);
503+
localThis._doubleLinkedList.Remove(localCacheItem);
504+
localThis._doubleLinkedList.AddFirst(localCacheItem);
499505
});
500506
}
501507

@@ -516,7 +522,11 @@ public bool TryRemove(TKey key, out TValue value)
516522
}
517523

518524
if (_maintainLRU)
519-
AddActionToEventQueue(() => _doubleLinkedList.Remove(cacheItem));
525+
{
526+
var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU
527+
var localThis = this;
528+
AddActionToEventQueue(() => localThis._doubleLinkedList.Remove(localCacheItem));
529+
}
520530

521531
value = cacheItem.Value;
522532
OnItemRemoved?.Invoke(cacheItem.Value);

0 commit comments

Comments
 (0)