Wednesday, January 13, 2016

Async http request

http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html


using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
namespace AsyncTests
{
    class Program
    {
        static async Task<string> GetBookAsync(string url)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    // by calling .Result you are performing a synchronous call
                    var responseContent = response.Content;
                    // by calling .Result you are synchronously reading the result
                    return await responseContent.ReadAsStringAsync();
                }
            }
            return null;
        }
        static void Main(string[] args)
        {
            // Async
            Stopwatch sw2 = new Stopwatch();
            sw2.Start();
            var result1 = GetBookAsync("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699");
            var result2 = GetBookAsync("https://www.googleapis.com/books/v1/volumes?q=isbn:1101875100");
            var result3 = GetBookAsync("https://www.googleapis.com/books/v1/volumes?q=isbn:1501115634");
            var result4 = GetBookAsync("https://www.googleapis.com/books/v1/volumes?q=isbn:0525478817");
            sw2.Stop();
            Console.WriteLine(sw2.ElapsedTicks);
            var allDone = Task.WhenAll(result1, result2, result3, result4);
            foreach (var result in allDone.Result)
            {
                // Callbacks are executed here
            }
            Console.ReadLine();
        }
    }
}


No comments:

Post a Comment