/// <summary> /// Invokes the logic of the middleware. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <returns>A <see cref="Task"/> that completes when the request leaves.</returns> public async Task Invoke(HttpContext context) { var waitInQueueTask = _requestQueue.TryEnterQueueAsync(); if (waitInQueueTask.IsCompletedSuccessfully && waitInQueueTask.Result) { RequestThrottlingLog.RequestRunImmediately(_logger, ActiveRequestCount); } else { RequestThrottlingLog.RequestEnqueued(_logger, ActiveRequestCount); await waitInQueueTask; RequestThrottlingLog.RequestDequeued(_logger, ActiveRequestCount); } if (!waitInQueueTask.Result) { RequestThrottlingLog.RequestRejectedQueueFull(_logger); context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; await _requestThrottlingOptions.OnRejected(context); return; } try { await _next(context); } finally { _requestQueue.Release(); } }