From 92fbb8a3e3161509ab9e22773300d930a65a7062 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 26 Jul 2023 11:02:45 -0400 Subject: [PATCH] Remove fast-path closures from EventBasedLRUCache --- .../EventBasedLRUCache.cs | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs index fa417848d4..09d9a2de8d 100644 --- a/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs +++ b/src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs @@ -390,10 +390,11 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime) cacheItem.ExpirationTime = expirationTime; if (_maintainLRU) { + var localCacheItem = cacheItem; // avoid closure when !_maintainLRU AddActionToEventQueue(() => { - _doubleLinkedList.Remove(cacheItem); - _doubleLinkedList.AddFirst(cacheItem); + _doubleLinkedList.Remove(localCacheItem); + _doubleLinkedList.AddFirst(localCacheItem); }); } } @@ -416,11 +417,12 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime) // add the new node to the _doubleLinkedList if _maintainLRU == true if (_maintainLRU) { + var localCacheItem = cacheItem; // avoid closure when !_maintainLRU 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); + _doubleLinkedList.Remove(localCacheItem); + _doubleLinkedList.AddFirst(localCacheItem); }); } @@ -492,10 +494,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 +520,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);