我正在使用线程池调用一些异步Web请求调用来发布数据
我在for循环中调用RunWebAccess函数
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 功能无效,因为它无法访问参数。
问题是我想在ProcessResults函数中传递参数并写入流。
根据代码,我不能在ProcessResults函数中使用全局变量或读取输入 (我想在ProcessResults函数中传递strdara,inttype)
答案 0 :(得分:2)
您可以使用lambda-notation进行回调,如下所示:
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);
}
答案 1 :(得分:0)
您可以发送一个新对象,其中包含要传递给回调的所有参数。喜欢:
IAsyncResult result = req.BeginGetRequestStream(
new AsyncCallback(ProcessResults),
new Tuple<HttpWebRequest,byte[]>(req, postData));