From 73ee0302ef723f14f024e8f3fb9e7396ec3d2583 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Wed, 26 Nov 2025 21:49:09 +0100 Subject: [PATCH] Limit concurrent HTTP requests with SemaphoreSlim Introduced a `SemaphoreSlim` with a concurrency limit of 5 to control the number of simultaneous HTTP requests. Updated the HTTP request logic to use `WaitAsync` and `Release` for managing access to the critical section. Wrapped the HTTP request handling in a `try-finally` block to ensure proper semaphore release, even in case of exceptions. This change improves resource management and prevents overwhelming the HTTP client or the target server. --- .../Commands/InvokeRecActionCommand.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/ReC.Application/RecActions/Commands/InvokeRecActionCommand.cs b/src/ReC.Application/RecActions/Commands/InvokeRecActionCommand.cs index 4d6ad11..e8ae005 100644 --- a/src/ReC.Application/RecActions/Commands/InvokeRecActionCommand.cs +++ b/src/ReC.Application/RecActions/Commands/InvokeRecActionCommand.cs @@ -21,14 +21,24 @@ public class InvokeRecActionCommandHandler(ISender sender, IHttpClientFactory cl var http = clientFactory.CreateClient(); + using var semaphore = new SemaphoreSlim(5); + var tasks = actions.Select(async action => { - var method = new HttpMethod(action.RestType.ToUpper()); - var msg = new HttpRequestMessage(method, action.EndpointUri); - - var response = await http.SendAsync(msg, cancel); - var body = await response.Content.ReadAsStringAsync(cancel); - var headers = response.Headers.ToDictionary(); + await semaphore.WaitAsync(cancel); + try + { + var method = new HttpMethod(action.RestType.ToUpper()); + var msg = new HttpRequestMessage(method, action.EndpointUri); + + var response = await http.SendAsync(msg, cancel); + var body = await response.Content.ReadAsStringAsync(cancel); + var headers = response.Headers.ToDictionary(); + } + finally + { + semaphore.Release(); + } }); await Task.WhenAll(tasks);