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
}
Comments
Post a Comment