473,698 Members | 1,947 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Async HttpWebRequest

APA
I've seen the MS sample async web request pattern and I ask is it really async if it is using a ManualResetEven t and setting WaitOne()? The
ManualResetEven t object is being declared as a static variable so isn't it causing problems with other threads that may be using the same class to
execute the async web request? If I remove the ManualResetEven t object will it be truly asynchronous and will I be losing something? Also, in my app
the web request is posting data.

For those that haven't seen the code it looks something like this:
public class AsyncWebRequest

public AsyncWebRequest (){}

public static ManualResetEven t allDone = new ManualResetEven t(false);

const int BUFFER_SIZE = 1024;

public void WebReq(string URL, string somedata)
{
try
{

if (URL.Trim() != "")
{
byte[] data = Encoding.ASCII. GetBytes(someda ta);

HttpWebRequest webRequest = (HttpWebRequest )System.Net.Web Request.Create( URL);
webRequest.Meth od = "POST";
webRequest.Cont entType = "applicatio n/x-www-form-urlencoded";
webRequest.Cont entLength = data.Length;

ManualResetEven t WaitHndle = new ManualResetEven t(false);
RequestState rs = new RequestState(Wa itHndle,this.De bug);

rs.Request = webRequest;
rs.DataToSend = data;

webRequest.Begi nGetRequestStre am(new AsyncCallback(R eadCallbackRequ est), rs);

IAsyncResult r = (IAsyncResult)w ebRequest.Begin GetResponse(new AsyncCallback(R espCallback), rs);

ThreadPool.Regi sterWaitForSing leObject(r.Asyn cWaitHandle, new WaitOrTimerCall back(ScanTimeou tCallback), rs, (30 * 1000), true);

allDone.WaitOne ();
rs.ResponseStre am.Close();

}
}
catch (WebException ex) { string str = ex.ToString(); }
catch (Exception ex) { string sr = ex.ToString(); }
}
private static void RespCallback(IA syncResult ar)
{
RequestState rs = (RequestState)a r.AsyncState;
try
{
WebRequest req = rs.Request;

WebResponse resp = req.EndGetRespo nse(ar);

Stream ResponseStream = resp.GetRespons eStream();

rs.ResponseStre am = ResponseStream;
rs.Waitone.Set( );

if (rs.Debug)
{
IAsyncResult iarRead = ResponseStream. BeginRead(rs.Bu fferRead, 0, BUFFER_SIZE, new AsyncCallback(R eadCallBack), rs);
}
}
catch (Exception ex)
{
rs.Waitone.Set( );
}
}
private static void ReadCallbackReq uest(IAsyncResu lt asynchronousRes ult)
{
RequestState rs = (RequestState)a synchronousResu lt.AsyncState;
try
{
HttpWebRequest request = rs.Request;

Stream postStream = request.EndGetR equestStream(as ynchronousResul t);

postStream.Writ e(rs.DataToSend , 0, rs.DataToSend.L ength);
postStream.Clos e();
}
catch (Exception ex)
{
}
allDone.Set();

}

private static void ScanTimeoutCall back(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)s tate;
if (reqState != null)
reqState.Reques t.Abort();
}
}

public class RequestState
{
const int BufferSize = 1024;
public byte[] DataToSend;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public Stream ResponseStream;
public ManualResetEven t Waitone;
public bool Debug;

public Decoder StreamDecode = Encoding.UTF8.G etDecoder();

public RequestState(Ma nualResetEvent waitHandle,bool debug)
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(S tring.Empty);
Request = null;
ResponseStream = null;
Waitone = waitHandle;
Debug = debug;
}
}
}
Jun 27 '08 #1
1 2848
normally you would put code you want to happen during the async request
before the wait. then after the wait, you put the code to handle the response.

the question is what do you want the thread to do during the request call?
after?

note: this code will not work from an asp.net application. if a webform, use
the builting async processing, if called from a web service, you will want to
use a WaitHandle rather than ManualResetEven t.

-- bruce (sqlwork.com)
"APA" wrote:
I've seen the MS sample async web request pattern and I ask is it really async if it is using a ManualResetEven t and setting WaitOne()? The
ManualResetEven t object is being declared as a static variable so isn't it causing problems with other threads that may be using the same class to
execute the async web request? If I remove the ManualResetEven t object will it be truly asynchronous and will I be losing something? Also, in my app
the web request is posting data.

For those that haven't seen the code it looks something like this:
public class AsyncWebRequest

public AsyncWebRequest (){}

public static ManualResetEven t allDone = new ManualResetEven t(false);

const int BUFFER_SIZE = 1024;

public void WebReq(string URL, string somedata)
{
try
{

if (URL.Trim() != "")
{
byte[] data = Encoding.ASCII. GetBytes(someda ta);

HttpWebRequest webRequest = (HttpWebRequest )System.Net.Web Request.Create( URL);
webRequest.Meth od = "POST";
webRequest.Cont entType = "applicatio n/x-www-form-urlencoded";
webRequest.Cont entLength = data.Length;

ManualResetEven t WaitHndle = new ManualResetEven t(false);
RequestState rs = new RequestState(Wa itHndle,this.De bug);

rs.Request = webRequest;
rs.DataToSend = data;

webRequest.Begi nGetRequestStre am(new AsyncCallback(R eadCallbackRequ est), rs);

IAsyncResult r = (IAsyncResult)w ebRequest.Begin GetResponse(new AsyncCallback(R espCallback), rs);

ThreadPool.Regi sterWaitForSing leObject(r.Asyn cWaitHandle, new WaitOrTimerCall back(ScanTimeou tCallback), rs, (30 * 1000), true);

allDone.WaitOne ();
rs.ResponseStre am.Close();

}
}
catch (WebException ex) { string str = ex.ToString(); }
catch (Exception ex) { string sr = ex.ToString(); }
}
private static void RespCallback(IA syncResult ar)
{
RequestState rs = (RequestState)a r.AsyncState;
try
{
WebRequest req = rs.Request;

WebResponse resp = req.EndGetRespo nse(ar);

Stream ResponseStream = resp.GetRespons eStream();

rs.ResponseStre am = ResponseStream;
rs.Waitone.Set( );

if (rs.Debug)
{
IAsyncResult iarRead = ResponseStream. BeginRead(rs.Bu fferRead, 0, BUFFER_SIZE, new AsyncCallback(R eadCallBack), rs);
}
}
catch (Exception ex)
{
rs.Waitone.Set( );
}
}
private static void ReadCallbackReq uest(IAsyncResu lt asynchronousRes ult)
{
RequestState rs = (RequestState)a synchronousResu lt.AsyncState;
try
{
HttpWebRequest request = rs.Request;

Stream postStream = request.EndGetR equestStream(as ynchronousResul t);

postStream.Writ e(rs.DataToSend , 0, rs.DataToSend.L ength);
postStream.Clos e();
}
catch (Exception ex)
{
}
allDone.Set();

}

private static void ScanTimeoutCall back(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)s tate;
if (reqState != null)
reqState.Reques t.Abort();
}
}

public class RequestState
{
const int BufferSize = 1024;
public byte[] DataToSend;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public Stream ResponseStream;
public ManualResetEven t Waitone;
public bool Debug;

public Decoder StreamDecode = Encoding.UTF8.G etDecoder();

public RequestState(Ma nualResetEvent waitHandle,bool debug)
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(S tring.Empty);
Request = null;
ResponseStream = null;
Waitone = waitHandle;
Debug = debug;
}
}
}
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
8178
by: Mike Cronin via DotNetMonster.com | last post by:
Hi there, Can anyone tell me what level of encryption is used when making an HTTPS POST request through an instance of the System.Net.HttpWebRequest object? Thanks much in advance! Mike Cronin Data On Call - Programmer
0
1836
by: Passynkov, Vadim | last post by:
I am using Asynchronous Query Processing interface from libpq library. And I got some strange results on Solaris My test select query is 'SELECT * from pg_user;' and I use select system synchronous I/O multiplexer in 'C' The first test sends 10000 select queries using 10 nonblocking connections to database ( PQsendQuery ). The second test sends the same 10000 select queries using 1 connection ( PQexec ).
16
12641
by: thomas peter | last post by:
I am building a precache engine... one that request over 100 pages on an remote server to cache them remotely... can i use the HttpWebRequest and WebResponse classes for this? or must i use the MSHTML objects to really load the HTML and request all of the images on site? string lcUrl = http://www.cnn.com; // *** Establish the request
10
2951
by: Shawn Meyer | last post by:
Hello - I am trying to write a class that has an async BeginX and EndX, plus the regular X syncronous method. Delegates seemed like the way to go, however, I still am having problems getting exactly what I want. Here are my goals 1. I would like the IAsyncResult that is returned by the Begin function to be able to be waited on or polled to check for completion. 2. The Begin function would take a callback, and the async process would
0
1133
by: mail.matty | last post by:
Hi All, I've hit a stumbling block and haven't been able to get past it yet. What I'm trying to do is create a library which makes Http Requests to a java servlet at the same time and then processes the response(s) when returned. I've got the following code written which generates the infamous 'Object Reference Not Set to an Instance of an Object error'. The error lies in this line of code (I've marked it with a ****** ******) in the...
0
1617
by: voipdealer | last post by:
I have to interface to a third-party application that receives HTTP POSTs with XML content to a certain port on the server. The server is *not* a web server, rather some custom server app written by the third-party, so it's behavior is not predictable or necessarily HTTP compliant. Therefore, I can't use the much simpler HttpWebRequest. Also, if I repeatedly open new connections to it, the server gets bogged down with authentication and...
1
4438
by: Demi | last post by:
I'm trying to use an Async="true" page to do an async HttpWebRequest. My code is based on the MSDN example: http://msdn2.microsoft.com/en-us/library/21k58ta7.aspx The problem I'm having is that I'm not sure how to wait until my response has finished arriving. It's jumping to EndGetAsyncData when I first get the response instead of when I finish reading it. Looking at the code I can see why it's doing this, but I'm not sure how I can...
7
5071
by: =?Utf-8?B?Q2FybG8gRm9saW5p?= | last post by:
Hi, I implemented asynchronous calls to a web resource (using HttpWebRequest) from asp.net 2.0. The request it's made asyncronously (I see that beginGetResponse returns immediately). The number of worker thread and completionPortThreads are over 300. Making 200 calls I see that 100 are queued. There's a counter telling how much async calls are handled? How can I raise the number of request handled?
10
4499
by: Frankie | last post by:
It appears that System.Random would provide an acceptable means through which to generate a unique value used to identify multiple/concurrent asynchronous tasks. The usage of the value under consideration here is that it is supplied to the AsyncOperationManager.CreateOperation(userSuppliedState) method... with userSuppliedState being, more or less, a taskId. In this case, the userSuppliedState {really taskId} is of the object type,...
0
8672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9155
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9018
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8858
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7711
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5859
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4360
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.