Showing posts with label async. Show all posts
Showing posts with label async. Show all posts

How to read webpage asynchronously in c#

most programming languages a called method is executed synchronously, i.e. in the thread of execution from which it is invoked. If the method needs a long time to completion, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
namespace AsyncDemo
{
class Program
    {
static void Main(string[] args)
        {
string url = @"http://microsoft.com";
            DownloadAsync(url);
            Console.WriteLine("Doing Some more work in main");
            Console.ReadLine();
        }
private static void DownloadAsync(string url)
        {
var httpwebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpwebRequest.BeginGetResponse(ar =>
                {
var webResponse = httpwebRequest.EndGetResponse(ar);
using (var responseStream = webResponse.GetResponseStream())
                    {
var manulaResetEvent = new ManualResetEvent(false);
//Set the buffer size
byte[] buffer = new byte[1024];
//Callback
                        AsyncCallback readCallback = null;
                        readCallback = ir =>
                            {
var bytesRead = responseStream.EndRead(ir);
if (bytesRead > 0)
                                {
                                    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
                                    responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                                }
else
                                {
//Alowing waiting thread to proceed
                                    manulaResetEvent.Set();
                                }
                            };
                        responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
//Block the current thread
                        manulaResetEvent.WaitOne();
                    }
                }, null);
        }
    }
}