我正在尝试执行某种与CMD的Ping命令类似的操作,即它将向服务器发出请求,等待一段时间,然后他们声明此请求的数据包已丢失,该请求是在我坐在HttpClient对象的Timeout属性之前的合理时间内完成,但是一旦完成请求,请求就保持超时(在设置Timeout属性之前大约需要1000毫秒才能从服务器获取数据)。 会有人知道为什么会这样吗?
public class TestPacketLoss
{
private HttpClient _client;
public TestPacketLoss()
{
_client = new HttpClient();
_client.BaseAddress = new Uri("https://localhost:5001/api/");
_client.Timeout = new TimeSpan(0, 0, 0, 0, 1500);
}
public async Task Start()
{
Stopwatch sw = new Stopwatch();
long milliseconds = 0;
int packetsLost = 0;
for (int i = 0; i < 60; i++)
{
sw.Restart();
HttpResponseMessage response;
try
{
response = await _client.GetAsync("Temprature/");
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
Console.WriteLine($"Request received in {sw.ElapsedMilliseconds} ms");
milliseconds += sw.ElapsedMilliseconds;
}
else
{
packetsLost++;
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed in {sw.ElapsedMilliseconds}");
packetsLost++;
}
}
Console.WriteLine($"Received 60 messages in avarage of {milliseconds / 60} ms");
Console.WriteLine($"Number of packets lost {packetsLost}");
}
}
更新
使用调试器进行的快速更新,我实际上发现,请求与失败之间经过的时间少于超时时间,这表明HttpClient计算超时的方式出了问题>