Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple test of HTTP Client under load with many simultaneous requests. For me this produces about 15000 requests in 20 seconds which is nearly on par with what the old HttpWebRequest client I used produced.
[TestClass]
public class HttpClientPerfTests
{
private string testUrl = "https://localhost:5001/api/artist/33";
private int counter = 0;
private bool cancel = false;
private HttpClient GetHttpClient(bool force = false)
{
if (!force && _httpClient != null) return _httpClient;
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromSeconds(60),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1),
MaxConnectionsPerServer = 200
};
_httpClient = new HttpClient(socketsHandler);
return _httpClient;
}
[TestMethod]
public async Task ThreadRequestsAsync()
{
int threadCount = 8;
Console.WriteLine("Threads:" + threadCount);
for (int i = 0; i < threadCount; i++)
{
//var t = new Thread(RunHttpRequestsAsync);
//t.Start();
await RunHttpRequestsAsync();
}
// let it run for a 20 secs
await Task.Delay(20000);
cancel = true;
Console.WriteLine(counter);
}
private HttpClient _httpClient;
async Task RunHttpRequestsAsync()
{
Task.Run(async () =>
{
while (!cancel)
{
await RunHttpRequestAsync();
}
}).FireAndForget();
}
async Task<int> RunHttpRequestAsync()
{
var client = GetHttpClient();
var resp = await client.GetAsync(testUrl);
_ = await resp.Content.ReadAsStringAsync();
Interlocked.Increment(ref counter);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment