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.
This commit is contained in:
@@ -21,7 +21,12 @@ public class InvokeRecActionCommandHandler(ISender sender, IHttpClientFactory cl
|
||||
|
||||
var http = clientFactory.CreateClient();
|
||||
|
||||
using var semaphore = new SemaphoreSlim(5);
|
||||
|
||||
var tasks = actions.Select(async action =>
|
||||
{
|
||||
await semaphore.WaitAsync(cancel);
|
||||
try
|
||||
{
|
||||
var method = new HttpMethod(action.RestType.ToUpper());
|
||||
var msg = new HttpRequestMessage(method, action.EndpointUri);
|
||||
@@ -29,6 +34,11 @@ public class InvokeRecActionCommandHandler(ISender sender, IHttpClientFactory cl
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user