【问题标题】:passing parameters to BeginGetRequestStream将参数传递给 BeginGetRequestStream
【发布时间】:2011-03-30 05:30:16
【问题描述】:

我正在使用线程池调用一些异步 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)

【问题讨论】:

    标签: asp.net asynchronous httpwebrequest


    【解决方案1】:

    您可以对回调使用 lambda 表示法,如下所示:

    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);
    }
    

    【讨论】:

      【解决方案2】:

      您可以发送一个新对象,其中包含您要传递给回调的所有参数。喜欢:

      IAsyncResult result = req.BeginGetRequestStream(
          new AsyncCallback(ProcessResults),
          new Tuple<HttpWebRequest,byte[]>(req, postData));
      

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 2013-11-19
        • 2011-01-06
        • 2013-07-19
        • 2020-05-02
        相关资源
        最近更新 更多