如何获取经过的时间在.net core中使用httpclient在异步/等待中获取REST GET请求

Pet*_*ete 3 c# async-await .net-core asp.net-core

当我用Task.Wait调用下面的方法DoRestCall时,经过的时间基本上显示为0(好吧,它显示3ms)。我知道这是因为异步/等待模式。我想获得完成其余呼叫所需的实际时间。我无法找到进入 HttpClient 内部来解决这个问题的方法。

public static async Task DoRestCall()
{
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync("https://http://myrest.com");
    if (response.IsSuccessStatusCode)
    {
        var sw = new Stopwatch();
        sw.Start();
        var x = await response.Content.ReadAsStringAsync();
        sw.Stop();
        Console.WriteLine($"{x.Length} {sw.ElapsedMilliseconds}");
    }
}
Run Code Online (Sandbox Code Playgroud)

Hun*_*ach 5

其他查看Elapsed TimeHttpClient的方式

1.将日志级别更改为InformationTrace

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      //"System.Net.Http.HttpClient": "Information"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

样本输出

info: System.Net.Http.HttpClient.MyClient.LogicalHandler[100]
  Start processing HTTP request GET https://api.github.com/repos/aspnet/docs/branches

info: System.Net.Http.HttpClient.MyClient.ClientHandler[100]
  Sending HTTP request GET https://api.github.com/repos/aspnet/docs/branches

info: System.Net.Http.HttpClient.MyClient.ClientHandler[101]
  Received HTTP response after 682.9818ms - OK

info: System.Net.Http.HttpClient.MyClient.LogicalHandler[101]
  End processing HTTP request after 693.1094ms - OK
Run Code Online (Sandbox Code Playgroud)

2.创建新的Handler

public class TimingHandler : DelegatingHandler
{
    private readonly ILogger<TimingHandler> _logger;

    public TimingHandler(ILogger<TimingHandler> logger)
    {
        _logger = logger;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        var sw = Stopwatch.StartNew();

        _logger.LogInformation("Starting request");

        var response = await base.SendAsync(request, cancellationToken);

        _logger.LogInformation($"Finished request in {sw.ElapsedMilliseconds}ms");

        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

更多细节