@@ -10,49 +10,49 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter
10
10
{
11
11
internal class QueuePolicy : IQueuePolicy , IDisposable
12
12
{
13
- private readonly int _maxConcurrentRequests ;
14
- private readonly int _requestQueueLimit ;
13
+ private readonly int _maxTotalRequest ;
15
14
private readonly SemaphoreSlim _serverSemaphore ;
16
15
17
16
private object _totalRequestsLock = new object ( ) ;
17
+
18
+ private readonly static ValueTask < bool > _falseValueTask = new ValueTask < bool > ( false ) ;
19
+
18
20
public int TotalRequests { get ; private set ; }
19
21
20
22
public QueuePolicy ( IOptions < QueuePolicyOptions > options )
21
23
{
22
- _maxConcurrentRequests = options . Value . MaxConcurrentRequests ;
23
- if ( _maxConcurrentRequests <= 0 )
24
+ if ( options . Value . MaxConcurrentRequests <= 0 )
24
25
{
25
- throw new ArgumentException ( nameof ( _maxConcurrentRequests ) , "MaxConcurrentRequests must be a positive integer." ) ;
26
+ throw new ArgumentException ( nameof ( options . Value . MaxConcurrentRequests ) , "MaxConcurrentRequests must be a positive integer." ) ;
26
27
}
27
28
28
- _requestQueueLimit = options . Value . RequestQueueLimit ;
29
- if ( _requestQueueLimit < 0 )
29
+ if ( options . Value . RequestQueueLimit < 0 )
30
30
{
31
- throw new ArgumentException ( nameof ( _requestQueueLimit ) , "The RequestQueueLimit cannot be a negative number." ) ;
31
+ throw new ArgumentException ( nameof ( options . Value . RequestQueueLimit ) , "The RequestQueueLimit cannot be a negative number." ) ;
32
32
}
33
33
34
- _serverSemaphore = new SemaphoreSlim ( _maxConcurrentRequests ) ;
34
+ _serverSemaphore = new SemaphoreSlim ( options . Value . MaxConcurrentRequests ) ;
35
+
36
+ _maxTotalRequest = options . Value . MaxConcurrentRequests + options . Value . RequestQueueLimit ;
35
37
}
36
38
37
- public async ValueTask < bool > TryEnterAsync ( )
39
+ public ValueTask < bool > TryEnterAsync ( )
38
40
{
39
41
// a return value of 'false' indicates that the request is rejected
40
42
// a return value of 'true' indicates that the request may proceed
41
43
// _serverSemaphore.Release is *not* called in this method, it is called externally when requests leave the server
42
44
43
45
lock ( _totalRequestsLock )
44
46
{
45
- if ( TotalRequests >= _requestQueueLimit + _maxConcurrentRequests )
47
+ if ( TotalRequests >= _maxTotalRequest )
46
48
{
47
- return false ;
49
+ return _falseValueTask ;
48
50
}
49
51
50
52
TotalRequests ++ ;
51
53
}
52
54
53
- await _serverSemaphore . WaitAsync ( ) ;
54
-
55
- return true ;
55
+ return AwaitSemaphore ( ) ;
56
56
}
57
57
58
58
public void OnExit ( )
@@ -69,5 +69,12 @@ public void Dispose()
69
69
{
70
70
_serverSemaphore . Dispose ( ) ;
71
71
}
72
+
73
+ private async ValueTask < bool > AwaitSemaphore ( )
74
+ {
75
+ await _serverSemaphore . WaitAsync ( ) ;
76
+
77
+ return true ;
78
+ }
72
79
}
73
80
}
0 commit comments