Pete
Pete

Reputation: 3451

How To Get Elapsed Time Getting REST GET request in async / await with httpclient in .net core

When I call the method DoRestCall below with Task.Wait, the elapsed time shows basically 0 (OK, it shows 3ms). I get that it is because of the async/await pattern. I want to get the actual time it took to complete the rest call. I can't figure out a way to get inside HttpClient to figure that out.

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}");
    }
}

Upvotes: 3

Views: 6427

Answers (2)

Hung Quach
Hung Quach

Reputation: 2177

Others way to view Elapsed Time of HttpClient

1.Change Log Level to Information or Trace

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      //"System.Net.Http.HttpClient": "Information"
    }
  }
}

Sample output

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

2.Creating a new 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;
    }
}

For more details

Upvotes: 5

Nathan Werry
Nathan Werry

Reputation: 886

You should move the stopwatch to include your .GetAsync call also.

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

Upvotes: 3

Related Questions