Skip to content

Instantly share code, notes, and snippets.

@RickStrahl
Created October 12, 2021 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickStrahl/e5e066f273e2a2a4602b3cbb3a633563 to your computer and use it in GitHub Desktop.
Save RickStrahl/e5e066f273e2a2a4602b3cbb3a633563 to your computer and use it in GitHub Desktop.
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