@@ -12,12 +12,11 @@ public sealed class AsyncLock<TKey>
1212{
1313 public AsyncLock ( int maxPoolSize = 64 )
1414 {
15- MaxPoolSize = maxPoolSize ;
15+ _pool = new Pool < AsyncLock > ( maxPoolSize ) ;
1616 }
1717
1818 private readonly IDictionary < TKey , AsyncLock > _locks = new Dictionary < TKey , AsyncLock > ( ) ;
19- private readonly IList < AsyncLock > _pool = new List < AsyncLock > ( ) ;
20- private readonly int MaxPoolSize ;
19+ private readonly Pool < AsyncLock > _pool ;
2120
2221 /// <summary>
2322 /// GetAsyncLock
@@ -28,34 +27,25 @@ private AsyncLock GetAsyncLock(TKey key)
2827 {
2928 if ( _locks . TryGetValue ( key , out AsyncLock ? asyncLock ) == false )
3029 {
31- //is idle AsyncLock available
32- if ( _pool . Count > 0 )
33- {
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 =>
30+ //create new AsyncLock
31+ _pool . GetOrCreate ( out asyncLock ,
32+ ( ) =>
4533 {
46- //is AsyncLock idle
47- if ( x . State == AsyncLockState . Idle )
34+ AsyncLock a = new AsyncLock ( _locks ) ;
35+ a . Released += x =>
4836 {
49- _locks . Remove ( key ) ;
50-
51- //add idle AsynLock to pool
52- if ( _pool . Count < MaxPoolSize )
37+ //is AsyncLock idle
38+ if ( x . State == AsyncLockState . Idle )
5339 {
40+ _locks . Remove ( key ) ;
41+
42+ //add idle AsynLock to pool
5443 _pool . Add ( x ) ;
5544 }
56- }
57- } ;
58- }
45+ } ;
46+
47+ return a ;
48+ } ) ;
5949
6050 _locks . Add ( key , asyncLock ) ;
6151 }
0 commit comments