Reputation: 21
I am using thread pool to call some asynchronous web request call for posting the data
I am calling RunWebAccess function in a for loop
public void RunWebAccess (string strdara, int inttype)
{
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://www.test.com");
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xmlvar);
req.Method = "POST";
req.ContentType = "text/xml";
req.ContentLength = requestBytes.Length;
IAsyncResult result =
req.BeginGetRequestStream(new AsyncCallback(ProcessResults), req);
}
private void ProcessResults(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
Stream postStream = request.EndGetRequestStream(result);
postStream.Write(result., 0, postData.Length ;
postStream.Close();
}
ProcessResults function is not working because it can not access the parameters.
The problem is I want to pass the parameters in ProcessResults function and write to stream.
As per code, I can not use global variable or read input in ProcessResults function.
(I want to pass the strdara,inttype in ProcessResults function)
Upvotes: 2
Views: 2688
Reputation: 3097
You could send a new object, containing all the parameters that you want to pass to the callback. Like:
IAsyncResult result = req.BeginGetRequestStream(
new AsyncCallback(ProcessResults),
new Tuple<HttpWebRequest,byte[]>(req, postData));
Upvotes: 1
Reputation: 19279
You could use lambda-notation for the callback, something like this:
public void RunWebAccess (string strdara, int inttype)
{
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://www.test.com");
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xmlvar);
req.Method = "POST";
req.ContentType = "text/xml";
req.ContentLength = requestBytes.Length;
IAsyncResult result = null;
result =
req.BeginGetRequestStream(ar =>
{
Stream postStream = request.EndGetRequestStream(result);
postStream.Write(result., 0, postData.Length ;
postStream.Close();
}
, req);
}
Upvotes: 2