Asynchronous Request in .NET (C#)

Tools Used : .NET SDK

Asynchronous Request

The System.Net classes use the standard .NET frameworks asynchronous programming model for asynchronous access to Internet resources. The BeginGetResponse and EndGetResponse methods of the WebRequest start and complete the asynchronous request for an Internet resource.

The following example program in C# demonstrates using asynchronous calls with the WebRequest class. The example program is a console program that takes a URI from the command line, requests the resource at the URI, and then prints the URI to the console as it is received from the Internet.

The program consists of two parts, the Main() function that reads the command line and makes a request to the URI entered on the command line, and the RespCallback() method that performs the work of reading the response from the Internet resources.

namespace AsynNetIO
{
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
/// <summary>
/// This Sample Demostrate the USE Asynchronis
/// </summary>
public class CAsync
{
const int MAX = 128;
public static void showUsage()
{
Console.WriteLine("Attempts to GET a URL");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine("CAsync URL");
Console.WriteLine("Examples:");
Console.WriteLine("CAsync http://www.microsoft.com");
}
private static void RespCallback(IAsyncResult ar)
{
HttpWebRequest req ;
HttpWebResponse resp ;
int BytesRead ;
StreamReader Reader ;
StringWriter Writer ;
req = ( HttpWebRequest)ar.AsyncObject;
resp = (HttpWebResponse)req.EndGetResponse(ar);
BytesRead = 0;
char[] Buffer=new char[MAX] ;
Reader =
new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
Writer =
new StringWriter();
BytesRead = Reader.Read(Buffer, 0, MAX);
while (BytesRead != 0 )
{
Writer.Write(Buffer, 0, MAX);
BytesRead = Reader.Read(Buffer, 0, MAX);
}
Console.WriteLine("Message = " + Writer.ToString());
}
public static int Main(string[] args)
{
Console.WriteLine("args {0} value {1}",args.Length,args[0]);
if (args.Length < 1)
{
showUsage();
return 0;
}
URI HttpSite ;
HttpWebRequest wreq ;
IAsyncResult r;
HttpSite =
new URI(args[0]);
wreq = (HttpWebRequest) WebRequestFactory.Create(HttpSite);
r = (IAsyncResult) wreq.BeginGetResponse(
new AsyncCallback(RespCallback), null); Thread.Sleep(30000);
Console.WriteLine("Exiting.");
return 0;
}
}
}

Did you like this article? You can send your comments to the author.


Similar Articles