在C#中,控制HTTP請求頻率通常涉及到使用異步編程、線程池或者第三方庫。以下是一些建議:
async
和await
關鍵字來實現異步編程。public async Task<string> SendRequestAsync(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
Task.Run
和SemaphoreSlim
來實現。public async Task SendRequestsAsync(string[] urls, int maxConcurrency)
{
SemaphoreSlim semaphore = new SemaphoreSlim(maxConcurrency);
foreach (var url in urls)
{
await semaphore.WaitAsync();
Task.Run(() =>
{
try
{
string response = SendRequestAsync(url).Result;
// 處理響應
}
catch (Exception ex)
{
// 處理異常
}
finally
{
semaphore.Release();
}
});
}
}
Flurl
和HttpClientFactory
。這些庫提供了更多的功能和靈活性,可以幫助你更好地管理HTTP請求。例如,使用HttpClientFactory
可以輕松地創建和管理HttpClient
實例,從而更好地控制請求頻率和連接池。
public class CustomHttpClientFactory : IHttpClientFactory
{
private readonly SemaphoreSlim _semaphore;
public CustomHttpClientFactory(int maxConcurrency)
{
_semaphore = new SemaphoreSlim(maxConcurrency);
}
public HttpClient CreateClient(string name)
{
return new HttpClient(_semaphore);
}
}
然后,在Startup.cs
中注冊自定義的HttpClientFactory
:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<CustomHttpClientFactory>(new CustomHttpClientFactory(maxConcurrency: 10));
services.AddHttpClient<IApiClient, ApiClient>();
}
這樣,你就可以在ApiClient
中使用IHttpClient
實例,它將遵循CustomHttpClientFactory
中定義的請求頻率限制。