E
E
evgsvg2021-07-27 14:57:42
C++ / C#
evgsvg, 2021-07-27 14:57:42

How in C# HttpClient to calculate the time to send a request, the time to wait for a response and the time to receive a response?

Good afternoon.
Friends, is it possible, using the standard C# HttpClient, to calculate the time for sending a request, the time for waiting for a response, and the time for receiving a response?

Those. not common runtime

watch.Start();
var response = await httpClient.SendAsync(httpMessage);
watch.Stop();


Something like that
watch.Start();
var response = await app.Client.GetAsync("test/GetTestMethod");
watch.Stop();
var requestTime = watch.ElapsedMilliseconds;
watch.Restart();
var content = await response.Content.ReadAsStringAsync();
watch.Stop();
var responseTime = watch.ElapsedMilliseconds;


I was hoping that if I measured the execution time of response.Content.ReadAsStringAsync(), I would get the desired result, but as I saw, this is just reading the result already obtained.

Has anyone come across a solution to this issue?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2021-07-27
@sarapinit

A quick look at the HttpClient code tells me that you can get the values ​​you want simply by running await later. But it would be better for someone to double-check me, because the code there is not the easiest.

watch.Start();
var responseTask = app.Client.GetAsync("test/GetTestMethod");
watch.Stop();
var requestTime = watch.ElapsedMilliseconds;
watch.Restart();
watch.Start();
var response = await responseTask;
watch.Stop();
var fromRequestToStartResponse = watch.ElapsedMilliseconds;
watch.Restart();
watch.Start();
var content = await response.Content.ReadAsStringAsync();
watch.Stop();
var fromStartResponseToEndResponse = watch.ElapsedMilliseconds;

E
evgsvg, 2021-07-27
@evgsvg

You need to additionally add HttpCompletionOption.ResponseHeadersRead to Get.
Otherwise, the entire response will be received in the line, and with HttpCompletionOption.ResponseHeadersRead, we are waiting for the header, and the response is received directly in
response = await responseTask;
await response.Content.CopyToAsync(fs);

startSendRequest = DateTime.UtcNow;
var responseTask = HttpClient.GetAsync("Test/GetFile", HttpCompletionOption.ResponseHeadersRead);
endSendRequest = DateTime.UtcNow;

startWaitingResponse = DateTime.UtcNow;
response = await responseTask;
endWaitingResponse = DateTime.UtcNow;

startGetResponse = DateTime.UtcNow;
var fs = new FileStream(@"C:\test\SampleFile.txt", FileMode.Create, FileAccess.Write, FileShare.None);
await response.Content.CopyToAsync(fs);
endGetResponse = DateTime.UtcNow;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question