Answer the question
In order to leave comments, you need to log in
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();
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;
Answer the question
In order to leave comments, you need to log in
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;
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 questionAsk a Question
731 491 924 answers to any question