Saturday 11 January 2014

Download a Html from web using Async - Await C# 5

         In this article we are going to see how to use the Async and Await and what is the difference the Async -await and  old Asynchronus format.In Generally when we using the Async amd await keyword the method should have a Async along with Task Return type. then we can mention the await keyword wherever the async method is call. Why we have to mention the Await instead of just mention the Async as in the return type, it is because in the Async process the execution of method is invoked and then the object is get disposed by the next line of execution, to avoid this we have to make await.

What is the Difference between the Async-Await and Old format async programing ?

          Generally if we are writing a asynchronous programming developers thought is , the thread is running in the background and the UI responsive will be in good state. Then this is the same for Async-Await , If we really see deeply there is a big difference is present, Actually when we use the thread to run in background it will run ,but when the I/O bound operation comes the thread execution is sleep or pause and the I/O operation starts the process when the I/O operation ends a signal is sent to the thread to start the thread from interrupt.
          So there is a Wait and sleep is maintain once the I/O operation starts. but in the Async-Await the program is running in background and when the I/O operation reaches then the I/O operation is execution starts but the Thread starts executing the next line of code instead of wait and it will receive a signal from the I/O once operation completes.

         So I/O operation bound is a major difference between the Thread in Asynchronous and Async-Await.
Now let we see in programming 

Asynchronous programming in C# 4

private static void DownloadHtmlOldAsync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            httprequest.BeginGetResponse(ar =>
            {
                var httpresponse = httprequest.EndGetResponse(ar);
                using (var resp = httpresponse.GetResponseStream())
                {
                    var buffer = new byte[2048];
                    var manualreset = new ManualResetEvent(false);
                    AsyncCallback readCallback = null;
                    readCallback = rasync =>
                    {
                        var bytesread = resp.EndRead(rasync);
                        if (bytesread > 0)
                        {
                            Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                            resp.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                        }
                        else
                        {
                            manualreset.Set();
                        }
                    };

                    resp.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                    manualreset.WaitOne();
                }

            }, null);

        }

Async - Await C# 5

 private static async Task DownloadHtmlNewAsync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            var webresponse = await httprequest.GetResponseAsync();
            using (var responsestream = webresponse.GetResponseStream())
            {
                var buffer = new byte[2048];
                int bytesread =0;
               
                while((bytesread= await responsestream.ReadAsync(buffer, 0, buffer.Length))>0)
                {
                    Console.WriteLine(Encoding.UTF8.GetString(buffer,0,bytesread));
                }
            }

        }


Synchronous Program

  private static void DownlaodHtmlSync(string url)
        {
            var httprequest = (HttpWebRequest)WebRequest.Create(url);
            var webresponse = httprequest.GetResponse();
            using(var respstream = webresponse.GetResponseStream())
            {
                var buffer = new byte[2048];
                int bytesread = 0;
                while((bytesread=respstream.Read(buffer,0,buffer.Length))>0)
                {
                    Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesread));
                }
            }
        }

      

Program

        static void Main(string[] args)
        {
            /* Read Html Page*/
            DownlaodHtmlSync("http://www.dotnetvisio.blogspot.com");
            Console.ReadLine();

        }

I hope from this article you can learn what is the usage of async - await , and major difference the Asynchronous program in C# 4 and 5

No comments:

Post a Comment