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:
parent
d80e0d3562
commit
73ee0302ef
@ -21,14 +21,24 @@ public class InvokeRecActionCommandHandler(ISender sender, IHttpClientFactory cl
|
|||||||
|
|
||||||
var http = clientFactory.CreateClient();
|
var http = clientFactory.CreateClient();
|
||||||
|
|
||||||
|
using var semaphore = new SemaphoreSlim(5);
|
||||||
|
|
||||||
var tasks = actions.Select(async action =>
|
var tasks = actions.Select(async action =>
|
||||||
{
|
{
|
||||||
var method = new HttpMethod(action.RestType.ToUpper());
|
await semaphore.WaitAsync(cancel);
|
||||||
var msg = new HttpRequestMessage(method, action.EndpointUri);
|
try
|
||||||
|
{
|
||||||
|
var method = new HttpMethod(action.RestType.ToUpper());
|
||||||
|
var msg = new HttpRequestMessage(method, action.EndpointUri);
|
||||||
|
|
||||||
var response = await http.SendAsync(msg, cancel);
|
var response = await http.SendAsync(msg, cancel);
|
||||||
var body = await response.Content.ReadAsStringAsync(cancel);
|
var body = await response.Content.ReadAsStringAsync(cancel);
|
||||||
var headers = response.Headers.ToDictionary();
|
var headers = response.Headers.ToDictionary();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
await Task.WhenAll(tasks);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user