Esempio n. 1
0
        /// <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.RequestRejectedQueueFull(_logger);
                context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
                return;
            }
            else if (!waitInQueueTask.IsCompletedSuccessfully)
            {
                RequestThrottlingLog.RequestEnqueued(_logger, ActiveRequestCount);
                var result = await waitInQueueTask;
                RequestThrottlingLog.RequestDequeued(_logger, ActiveRequestCount);

                Debug.Assert(result);
            }
            else
            {
                RequestThrottlingLog.RequestRunImmediately(_logger, ActiveRequestCount);
            }

            try
            {
                await _next(context);
            }
            finally
            {
                _requestQueue.Release();
            }
        }
Esempio n. 2
0
        /// <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.EnterQueue();

            if (waitInQueueTask.IsCompletedSuccessfully)
            {
                RequestThrottlingLog.RequestRunImmediately(_logger);
            }
            else
            {
                RequestThrottlingLog.RequestEnqueued(_logger, WaitingRequests);
                await waitInQueueTask;
                RequestThrottlingLog.RequestDequeued(_logger, WaitingRequests);
            }

            try
            {
                await _next(context);
            }
            finally
            {
                _requestQueue.Release();
            }
        }