Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpClient response time when running in parallel

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?

like image 641
Daniel Lang Avatar asked Jan 05 '13 23:01

Daniel Lang


1 Answers

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);
    }
}
like image 166
ollifant Avatar answered Sep 28 '22 03:09

ollifant