Skip to content

Commit 863219b

Browse files
Faster locking on .NET 9.0+ using System.Threading.Lock (#12)
* Faster locking on .NET 9.0+ using System.Threading.Lock * whitespaces * proper comment --------- Co-authored-by: Alex Yumashev <jitbit+github@gmail.com>
1 parent b516c0a commit 863219b

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

FastCache/FastCache.cs

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

22+
private readonly Lock _lock = new();
2223
private readonly Timer _cleanUpTimer;
2324
private readonly EvictionCallback _itemEvicted;
2425

@@ -65,7 +66,7 @@ await FastCacheStatics.GlobalStaticLock.WaitAsync()
6566
public void EvictExpired()
6667
{
6768
//Eviction already started by another thread? forget it, lets move on
68-
if (Monitor.TryEnter(_cleanUpTimer)) //use the timer-object for our lock, it's local, private and instance-type, so its ok
69+
if (_lock.TryEnter()) //use the new System.Threading.Lock class for faster locking in .NET9+
6970
{
7071
List<TKey> evictedKeys = null; // Batch eviction callbacks
7172
try
@@ -90,7 +91,7 @@ public void EvictExpired()
9091
}
9192
finally
9293
{
93-
Monitor.Exit(_cleanUpTimer);
94+
_lock.Exit();
9495
}
9596

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

FastCache/FastCache.csproj

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
4-
<TargetFrameworks>net6.0;net8.0;net10.0</TargetFrameworks>
4+
<TargetFrameworks>net6.0;net8.0;net9.0;net10.0</TargetFrameworks>
5+
<LangVersion>latest</LangVersion>
56
<PackageId>Jitbit.FastCache</PackageId>
67
<Title>FastCache</Title>
78
<Authors>Alex from Jitbit</Authors>
@@ -27,4 +28,11 @@
2728
</None>
2829
</ItemGroup>
2930

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+
3038
</Project>

0 commit comments

Comments
 (0)