Search code examples
c#asynchronoustask-parallel-library

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?


Solution

  • I would probably try something like the following:

    EDIT: Updated to make the HttpClient a static instance.

    static HttpClient client = new HttpClient();
    
    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();
        var result = await client.GetAsync(url);
        return new Tuple<HttpResponseMessage, TimeSpan>(result, stopWatch.Elapsed);
    }