简体   繁体   English

C#HttpClient如何计算发送请求的时间、等待响应的时间和接收响应的时间?

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

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.在我看来, startWaitingResponse 和 endWaitingResponse 变量正在计算总响应时间(带下载文件),而不是等待响应。 Is it possible to calculate "waiting response for download" and "download time"?是否可以计算“等待下载响应”和“下载时间”?

Pass HttpCompletionOption.ResponseHeadersRead :通过HttpCompletionOption.ResponseHeadersRead

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

Side note: prefer using Stopwatch for timing things.旁注:更喜欢使用Stopwatch来计时。 DateTime.UtcNow can jump forwards or backwards in time due to daylight savings time changes.由于夏令时的变化, DateTime.UtcNow可以在时间上向前或向后跳跃。 DateTime.UtcNow is not accurate for timing small amounts of time. DateTime.UtcNow对于少量时间的计时并不准确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM