Friday, 29 November 2013

async and await - 2

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 DemoCustomDownloader");

            string text = DemoCustomDownloader("http://www.pluralsight.com").Result;
            Console.WriteLine(text);

            Console.WriteLine("Called DemoCustomDownloader");

            Console.ReadKey();
        }

        private async static Task DemoCustomDownloader(string uri)
        {
            CustomDownloader downloader = new CustomDownloader();
            Task customDownloaderTask = Task.Factory.FromAsync(downloader.BeginDownload, downloader.EndDownload, uri);
           
            return await customDownloaderTask;
        }
    }





    public class CustomDownloader
    {
        private WebClient client = new WebClient();

        public IAsyncResult BeginDownload(AsyncCallback callback, object state)
        {
            Func downloader = this.Download;

            return downloader.BeginInvoke(state.ToString(), callback, null);
        }

        public string EndDownload(IAsyncResult result)
        {
            Func downloader = (result as AsyncResult).AsyncDelegate as Func;

            return downloader.EndInvoke(result);
        }

        private string Download(string uri)
        {
            return this.client.DownloadString(uri);
        }
    }
}

No comments: