11using System . Collections . Concurrent ;
2+ using Microsoft . Extensions . Logging ;
23
34namespace Netcorext . Extensions . Threading ;
45
5- public class KeyCountLocker
6+ public class KeyCountLocker : KeyLocker
67{
78 private readonly long _minimum ;
89 private readonly long ? _maximum ;
910 private static readonly ConcurrentDictionary < string , KeyLockerState < long > > CountLockers = new ( ) ;
10- private static readonly KeyLocker Locker = new ( ) ;
1111
1212 public KeyCountLocker ( long minimum = 1 , long ? maximum = null )
1313 {
1414 _minimum = minimum ;
1515 _maximum = maximum ;
1616 }
1717
18+ public KeyCountLocker ( long minimum = 1 , long ? maximum = null , long deadLockTimes = DEFAULT_DEAD_LOCK_TIMES , ILogger ? logger = null ) : base ( deadLockTimes , logger )
19+ {
20+ _minimum = minimum ;
21+ _maximum = maximum ;
22+ }
23+
1824 public async Task < bool > IncrementAsync ( string key , CancellationToken cancellationToken = default )
1925 {
2026 var newLocker = new KeyLockerState < long >
@@ -23,33 +29,33 @@ public async Task<bool> IncrementAsync(string key, CancellationToken cancellatio
2329 } ;
2430 try
2531 {
26- await Locker . WaitAsync ( key , cancellationToken ) ;
32+ await WaitAsync ( key , cancellationToken ) ;
2733
2834 if ( ! CountLockers . TryGetValue ( key , out var oldLocker ) )
2935 return CountLockers . TryAdd ( key , newLocker ) ;
3036
3137 if ( oldLocker . State + 1 > _maximum )
3238 return false ;
33-
39+
3440 newLocker . State = oldLocker . State + 1 ;
35-
41+
3642 return CountLockers . TryUpdate ( key , newLocker , oldLocker ) ;
3743 }
3844 finally
3945 {
40- Locker . Release ( key ) ;
46+ Release ( key ) ;
4147 }
4248 }
4349
4450 public async Task < bool > DecrementAsync ( string key , CancellationToken cancellationToken = default )
4551 {
4652 try
4753 {
48- await Locker . WaitAsync ( key , cancellationToken ) ;
54+ await WaitAsync ( key , cancellationToken ) ;
4955
5056 if ( ! CountLockers . TryGetValue ( key , out var oldLocker ) )
5157 return true ;
52-
58+
5359 var newLocker = new KeyLockerState < long >
5460 {
5561 State = oldLocker . State - 1
@@ -62,7 +68,7 @@ public async Task<bool> DecrementAsync(string key, CancellationToken cancellatio
6268 }
6369 finally
6470 {
65- Locker . Release ( key ) ;
71+ Release ( key ) ;
6672 }
6773 }
6874
@@ -73,4 +79,4 @@ public Task<long> GetAsync(string key, CancellationToken cancellationToken = def
7379
7480 return Task . FromResult ( locker . State ) ;
7581 }
76- }
82+ }
0 commit comments