I've seen the MS sample async web request pattern and I ask is it really async if it is using a ManualResetEvent and setting WaitOne()? The
ManualResetEvent 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 ManualResetEvent 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 ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public void WebReq(string URL, string somedata)
{
try
{
if (URL.Trim() != "")
{
byte[] data = Encoding.ASCII.GetBytes(somedata);
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = data.Length;
ManualResetEvent WaitHndle = new ManualResetEvent(false);
RequestState rs = new RequestState(WaitHndle,this.Debug);
rs.Request = webRequest;
rs.DataToSend = data;
webRequest.BeginGetRequestStream(new AsyncCallback(ReadCallbackRequest), rs);
IAsyncResult r = (IAsyncResult)webRequest.BeginGetResponse(new AsyncCallback(RespCallback), rs);
ThreadPool.RegisterWaitForSingleObject(r.AsyncWait Handle, new WaitOrTimerCallback(ScanTimeoutCallback), rs, (30 * 1000), true);
allDone.WaitOne();
rs.ResponseStream.Close();
}
}
catch (WebException ex) { string str = ex.ToString(); }
catch (Exception ex) { string sr = ex.ToString(); }
}
private static void RespCallback(IAsyncResult ar)
{
RequestState rs = (RequestState)ar.AsyncState;
try
{
WebRequest req = rs.Request;
WebResponse resp = req.EndGetResponse(ar);
Stream ResponseStream = resp.GetResponseStream();
rs.ResponseStream = ResponseStream;
rs.Waitone.Set();
if (rs.Debug)
{
IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
}
}
catch (Exception ex)
{
rs.Waitone.Set();
}
}
private static void ReadCallbackRequest(IAsyncResult asynchronousResult)
{
RequestState rs = (RequestState)asynchronousResult.AsyncState;
try
{
HttpWebRequest request = rs.Request;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(rs.DataToSend, 0, rs.DataToSend.Length);
postStream.Close();
}
catch (Exception ex)
{
}
allDone.Set();
}
private static void ScanTimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)state;
if (reqState != null)
reqState.Request.Abort();
}
}
public class RequestState
{
const int BufferSize = 1024;
public byte[] DataToSend;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public Stream ResponseStream;
public ManualResetEvent Waitone;
public bool Debug;
public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public RequestState(ManualResetEvent waitHandle,bool debug)
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(String.Empty);
Request = null;
ResponseStream = null;
Waitone = waitHandle;
Debug = debug;
}
}
} 1 2834
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 ManualResetEvent.
-- 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 ManualResetEvent and setting WaitOne()? The
ManualResetEvent 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 ManualResetEvent 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 ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public void WebReq(string URL, string somedata)
{
try
{
if (URL.Trim() != "")
{
byte[] data = Encoding.ASCII.GetBytes(somedata);
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = data.Length;
ManualResetEvent WaitHndle = new ManualResetEvent(false);
RequestState rs = new RequestState(WaitHndle,this.Debug);
rs.Request = webRequest;
rs.DataToSend = data;
webRequest.BeginGetRequestStream(new AsyncCallback(ReadCallbackRequest), rs);
IAsyncResult r = (IAsyncResult)webRequest.BeginGetResponse(new AsyncCallback(RespCallback), rs);
ThreadPool.RegisterWaitForSingleObject(r.AsyncWait Handle, new WaitOrTimerCallback(ScanTimeoutCallback), rs, (30 * 1000), true);
allDone.WaitOne();
rs.ResponseStream.Close();
}
}
catch (WebException ex) { string str = ex.ToString(); }
catch (Exception ex) { string sr = ex.ToString(); }
}
private static void RespCallback(IAsyncResult ar)
{
RequestState rs = (RequestState)ar.AsyncState;
try
{
WebRequest req = rs.Request;
WebResponse resp = req.EndGetResponse(ar);
Stream ResponseStream = resp.GetResponseStream();
rs.ResponseStream = ResponseStream;
rs.Waitone.Set();
if (rs.Debug)
{
IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
}
}
catch (Exception ex)
{
rs.Waitone.Set();
}
}
private static void ReadCallbackRequest(IAsyncResult asynchronousResult)
{
RequestState rs = (RequestState)asynchronousResult.AsyncState;
try
{
HttpWebRequest request = rs.Request;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(rs.DataToSend, 0, rs.DataToSend.Length);
postStream.Close();
}
catch (Exception ex)
{
}
allDone.Set();
}
private static void ScanTimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)state;
if (reqState != null)
reqState.Request.Abort();
}
}
public class RequestState
{
const int BufferSize = 1024;
public byte[] DataToSend;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public Stream ResponseStream;
public ManualResetEvent Waitone;
public bool Debug;
public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public RequestState(ManualResetEvent waitHandle,bool debug)
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(String.Empty);
Request = null;
ResponseStream = null;
Waitone = waitHandle;
Debug = debug;
}
}
} This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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: 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...
|
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...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
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,...
|
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...
|
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,...
| |