In my ASP.NET MVC4 application I have a controller action in which I go out to several external websites and collect information which I show on my page in an aggregated way. Obviously, I want to do this in parallel, so I have written my code similar to this:
var client1 = new HttpClient().GetAsync("http://google.com");
var client2 = new HttpClient().GetAsync("http://stackoverflow.com");
var client3 = new HttpClient().GetAsync("http://twitter.com");
var result1 = client1.Result;
var result2 = client2.Result;
var result3 = client3.Result;
How can I find out how long each request took to finish, so that I can display that information on my page?
I would probably try something like the following:
private async void _HttpServerDemo()
{
var info1 = _GetHttpWithTimingInfo("http://google.com");
var info2 = _GetHttpWithTimingInfo("http://stackoverflow.com");
var info3 = _GetHttpWithTimingInfo("http://twitter.com");
await Task.WhenAll(info1, info2, info3);
Console.WriteLine("Request1 took {0}", info1.Result);
Console.WriteLine("Request2 took {0}", info2.Result);
Console.WriteLine("Request3 took {0}", info3.Result);
}
private async Task<Tuple<HttpResponseMessage, TimeSpan>> _GetHttpWithTimingInfo(string url)
{
var stopWatch = Stopwatch.StartNew();
using (var client = new HttpClient())
{
var result = await client.GetAsync(url);
return new Tuple<HttpResponseMessage, TimeSpan>(result, stopWatch.Elapsed);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With