File tree Expand file tree Collapse file tree 1 file changed +29
-5
lines changed Expand file tree Collapse file tree 1 file changed +29
-5
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,14 @@ namespace AsyncKeyLock;
1010public sealed class AsyncLock < TKey >
1111 where TKey : notnull
1212{
13+ public AsyncLock ( int maxPoolSize = 64 )
14+ {
15+ MaxPoolSize = maxPoolSize ;
16+ }
17+
1318 private readonly IDictionary < TKey , AsyncLock > _locks = new Dictionary < TKey , AsyncLock > ( ) ;
19+ private readonly IList < AsyncLock > _pool = new List < AsyncLock > ( ) ;
20+ private readonly int MaxPoolSize ;
1421
1522 /// <summary>
1623 /// GetAsyncLock
@@ -21,17 +28,34 @@ private AsyncLock GetAsyncLock(TKey key)
2128 {
2229 if ( _locks . TryGetValue ( key , out AsyncLock ? asyncLock ) == false )
2330 {
24- asyncLock = new AsyncLock ( _locks ) ;
25- asyncLock . Released += x =>
31+ //is idle AsyncLock available
32+ if ( _pool . Count > 0 )
2633 {
27- lock ( _locks )
34+ int lastPos = _pool . Count - 1 ;
35+
36+ asyncLock = _pool [ lastPos ] ;
37+
38+ _pool . RemoveAt ( lastPos ) ;
39+ }
40+ else
41+ {
42+ //create new AsyncLock
43+ asyncLock = new AsyncLock ( _locks ) ;
44+ asyncLock . Released += x =>
2845 {
46+ //is AsyncLock idle
2947 if ( x . State == AsyncLockState . Idle )
3048 {
3149 _locks . Remove ( key ) ;
50+
51+ //add idle AsynLock to pool
52+ if ( _pool . Count < MaxPoolSize )
53+ {
54+ _pool . Add ( x ) ;
55+ }
3256 }
33- }
34- } ;
57+ } ;
58+ }
3559
3660 _locks . Add ( key , asyncLock ) ;
3761 }
You can’t perform that action at this time.
0 commit comments