Skip to content

Commit 4c78866

Browse files
committed
Refactor locking mechanism for compatibility with .NET 9.0+ and remove obsolete package reference
1 parent f9f01cd commit 4c78866

2 files changed

Lines changed: 13 additions & 8 deletions

File tree

FastCache/FastCache.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ public class FastCache<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>,
1919
{
2020
private readonly ConcurrentDictionary<TKey, TtlValue> _dict = new();
2121

22+
#if NET9_0_OR_GREATER
2223
private readonly Lock _lock = new();
24+
#else
25+
private readonly object _lock = new();
26+
#endif
2327
private readonly Timer _cleanUpTimer;
2428
private readonly EvictionCallback _itemEvicted;
2529

@@ -66,7 +70,11 @@ await FastCacheStatics.GlobalStaticLock.WaitAsync()
6670
public void EvictExpired()
6771
{
6872
//Eviction already started by another thread? forget it, lets move on
73+
#if NET9_0_OR_GREATER
6974
if (_lock.TryEnter()) //use the new System.Threading.Lock class for faster locking in .NET9+
75+
#else
76+
if (Monitor.TryEnter(_lock))
77+
#endif
7078
{
7179
List<TKey> evictedKeys = null; // Batch eviction callbacks
7280
try
@@ -91,7 +99,11 @@ public void EvictExpired()
9199
}
92100
finally
93101
{
94-
_lock.Exit();
102+
#if NET9_0_OR_GREATER
103+
_lock.Exit();
104+
#else
105+
Monitor.Exit(_lock);
106+
#endif
95107
}
96108

97109
// Trigger batched eviction callbacks outside the loop to prevent flooding the thread pool

FastCache/FastCache.csproj

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,4 @@
2828
</None>
2929
</ItemGroup>
3030

31-
<ItemGroup>
32-
<PackageReference Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net9.0'))" Include="Backport.System.Threading.Lock" Version="3.1.5">
33-
<PrivateAssets>all</PrivateAssets>
34-
<IncludeAssets>analyzers</IncludeAssets>
35-
</PackageReference>
36-
</ItemGroup>
37-
3831
</Project>

0 commit comments

Comments
 (0)