0

I have the following code

DateTime startSendRequest;
DateTime endSendRequest;
DateTime startWaitingResponse;
DateTime endWaitingResponse;
DateTime startGetResponse;
DateTime endGetResponse;
HttpResponseMessage response;

startSendRequest = DateTime.UtcNow;
var responseTask = HttpClient.GetAsync("Test/GetFile");
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;

It seems to me that the startWaitingResponse and endWaitingResponse variables are calculating the total response time (with download file), rather than waiting for a response. Is it possible to calculate "waiting response for download" and "download time"?

  • (Assigning from `DateTime.UtcNow` twice in a row looks debatable. I don't like it for increased intrusiveness of timing like this.) – greybeard Jul 28 '21 at 03:37

1 Answers1

3

Pass HttpCompletionOption.ResponseHeadersRead:

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

Side note: prefer using Stopwatch for timing things. DateTime.UtcNow can jump forwards or backwards in time due to daylight savings time changes. DateTime.UtcNow is not accurate for timing small amounts of time.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 1
    Actually UTC [is immune](https://stackoverflow.com/questions/62151/datetime-now-vs-datetime-utcnow/52625078#52625078) to daylight saving time adjustments. [I've made the same mistake myself](https://stackoverflow.com/questions/68331666/is-there-a-way-to-lock-a-concurrent-dictionary-from-being-used/68337246#comment120775575_68337246) recently. – Theodor Zoulias Jul 27 '21 at 18:44
  • thank you!))) it's work Stopwatch is faster, but i need datetime – Evgeny Nazarchuk Jul 27 '21 at 19:31