From ac018e449de80a91dc621b8f0464e8ead0f3db8d Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 27 Jul 2023 11:59:36 -0400 Subject: [PATCH] Remove fast-path closures from EventBasedLRUCache (#2170) --- .../EventBasedLRUCache.cs | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs index fa417848d4..7d642bd359 100644 --- a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs +++ b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs @@ -390,10 +390,12 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime) cacheItem.ExpirationTime = expirationTime; if (_maintainLRU) { + var localCacheItem = cacheItem; // avoid closure when !_maintainLRU + var localThis = this; AddActionToEventQueue(() => { - _doubleLinkedList.Remove(cacheItem); - _doubleLinkedList.AddFirst(cacheItem); + localThis._doubleLinkedList.Remove(localCacheItem); + localThis._doubleLinkedList.AddFirst(localCacheItem); }); } } @@ -416,11 +418,13 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime) // add the new node to the _doubleLinkedList if _maintainLRU == true if (_maintainLRU) { + var localNewCacheItem = newCacheItem; // avoid closure when !_maintainLRU + var localThis = this; AddActionToEventQueue(() => { // Add a remove operation in case two threads are trying to add the same value. Only the second remove will succeed in this case. - _doubleLinkedList.Remove(newCacheItem); - _doubleLinkedList.AddFirst(newCacheItem); + localThis._doubleLinkedList.Remove(localNewCacheItem); + localThis._doubleLinkedList.AddFirst(localNewCacheItem); }); } @@ -492,10 +496,12 @@ public bool TryGetValue(TKey key, out TValue value) // make sure node hasn't been removed by a different thread if (_maintainLRU) { + var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU + var localThis = this; AddActionToEventQueue(() => { - _doubleLinkedList.Remove(cacheItem); - _doubleLinkedList.AddFirst(cacheItem); + localThis._doubleLinkedList.Remove(localCacheItem); + localThis._doubleLinkedList.AddFirst(localCacheItem); }); } @@ -516,7 +522,11 @@ public bool TryRemove(TKey key, out TValue value) } if (_maintainLRU) - AddActionToEventQueue(() => _doubleLinkedList.Remove(cacheItem)); + { + var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU + var localThis = this; + AddActionToEventQueue(() => localThis._doubleLinkedList.Remove(localCacheItem)); + } value = cacheItem.Value; OnItemRemoved?.Invoke(cacheItem.Value);