Friday, 29 November 2013

async and await - 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Calling DownloadHeaders");

            DownloadHeaders("http://www.pluralsight.com");

            Console.WriteLine("Called DownloadHeaders");

            Console.ReadKey();
        }

        private async static void DownloadHeaders(string url)
        {
            HttpWebRequest request = WebRequest.Create("http://www.pluralsight.com") as HttpWebRequest;

            request.Method = "HEAD";
            using (var response = await request.GetResponseAsync() as HttpWebResponse)
            {
                PrintHeadersUsingLinq(response.Headers);
            }           
        }

        private static void PrintHeadersUsingLinq(WebHeaderCollection headers)
        {
            var keyValuePairs = from key in headers.AllKeys
                       select string.Format("{0}:{1}", key, headers[key]);

            Console.WriteLine(string.Join(Environment.NewLine, keyValuePairs));
        }
    }
}

No comments: