In C# How to Find Duration of Web API Calling Another API and Complete Response Time

In this article you will see how to find time duration of web api calling another web api and its complete response time. In C#, you can use the Stopwatch class to measure the duration of a web API call. Here is an example of how you can use it to measure the time it takes to call another API and receive a response:

using System;
using System.Diagnostics;
using System.Net.Http;

class Program {
    static void Main(string[] args) {
        var client = new HttpClient();
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        var response = client.GetAsync("https://example.com/api").Result;
        response.EnsureSuccessStatusCode();
        stopwatch.Stop();
        var duration = stopwatch.Elapsed;
        Console.WriteLine("API call and response time: {0}", duration);
    }
}

This code uses the GetAsync method of the HttpClient class to asynchronously call the API, and the Result property to wait for the response. The EnsureSuccessStatusCode method is used to throw an exception if the API returns a non-success status code. The Stopwatch class is used to measure the time it takes for the API call and response. The Elapsed property of the stopwatch returns the duration of the operation as a TimeSpan object.

It's worth noting that you should dispose the HttpClient when you're done with it, because it is a IDisposable object.

using (var client = new HttpClient())
{
    //Your code here
}

In case of calling multiple web api, you can use like below,

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;

class Program {
    static async Task Main(string[] args) {
        var client = new HttpClient();

        var stopwatch = new Stopwatch();
        stopwatch.Start();

        var task1 = client.GetAsync("https://example.com/api1");
        var task2 = client.GetAsync("https://example.com/api2");
        var task3 = client.GetAsync("https://example.com/api3");
        var responses = await Task.WhenAll(task1, task2, task3);

        stopwatch.Stop();
        var duration = stopwatch.Elapsed;
        Console.WriteLine("API call and response time: {0}", duration);
    }
}

Note that you should check the status code of each response individually to ensure that all the calls were successful, by using the EnsureSuccessStatusCode method or by checking the StatusCode property of the HttpResponseMessage object.

Happy PC (Programming / Configuring)

Comments

Popular posts from this blog

In C# CSOM How to Delete Folders Recursively, Sub-Folders, Files in SharePoint Online Document Library

How Get, Set, Delete Permission on SharePoint Online Site using Graph API

What is SharePoint online default authentication method? And which credential flow it is using to authenticate?