# 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;
namespace AsyncDemo
{
class Program
{
static void Main(string[] args)
{
string url = @"http://microsoft.com";
Console.WriteLine("Doing Some more work in main");
}
{
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
{
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
}
else
{
manulaResetEvent.Set();
}
};
manulaResetEvent.WaitOne();
}
}, null);
}
}
}

Reactions