2011-07-29 43 views
0

當我嘗試在第一個方法中點擊按鈕時,它爲loop.But創建異步http請求,但我無法將該參數傳遞給我的異步回調函數。 我想做的事情,我想通過使用POST方法發送內部的循環ID。HttpWebRequest AsyncCallback參數問題

void Button3Click(object sender, EventArgs e) 
    {    
     for(int i = Convert.ToInt32(startno3.Text); i<Convert.ToInt32(endno3.Text); i++) {     
      ASCIIEncoding encoding=new ASCIIEncoding(); 
      string postData="id=1";     
      qstr3 = encoding.GetBytes(postData);     

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/ornek/1.php"); 
      if(key1.Text!="") { 
       request.Headers.Add("Cookie", "PHPSESSID=" + key1.Text);      
      } 
      request.Method = "POST"; 
      request.ContentType="application/x-www-form-urlencoded"; 
      request.ContentLength = data.Length; 
      IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback(EndScanFeeds), request);  
     } 
    } 

    public void EndScanFeeds(IAsyncResult result) { 
     HttpWebRequest request = null; 
     HttpWebResponse response = null; 
     Stream stream = null; 
     StreamReader streamReader = null; 
     try { 
      request = (HttpWebRequest)result.AsyncState; 
      response = (HttpWebResponse)request.EndGetResponse(result); 
      stream = response.GetResponseStream(); 
      streamReader = new StreamReader(stream); 
      string feedData = streamReader.ReadToEnd(); 
      response.Close(); 
      stream.Close(); 
      streamReader.Close(); 
      MessageBox.Show(feedData); 

     } 
     catch(Exception ex) { 
      throw(ex); 
     } 
     finally { 
      if(response != null) 
       response.Close(); 
      if(stream != null) 
       stream.Close(); 
      if(streamReader != null) 
       streamReader.Close(); 
     } 
    } c 

回答

0

您需要的ID添加作爲查詢字符串參數傳遞給HttpWebRequest的(你沒有把它做後用qstr3任何東西)。

雖然您設置ContentType和ContentLength,但您並未傳遞任何實際內容。

但是,我擔心的是,並行引發(可能)很多簡單的異步HttpWebRequests。如果其中有相當多的人,我希望壞事開始發生。

考慮是否正確的做法。可以修改1.php以便一次獲取更多的ID嗎?

0

爲什麼你不能傳遞參數給你的函數? 您正在使用request作爲BeginGetResponse的第二個參數 - 您可以隨意傳遞任何自定義對象而不是該對象,同時持有參數和對請求的引用,並將result.AsyncState轉換爲該對象類型,而不是轉換爲HttpWebRequest

但實際上,如果您需要發送您的ID,您需要在異步request.BeginGetResponse操作之前獲取請求流 - 例如從您的請求獲取GetRequestStream()並在那裏寫入數據(或再次作爲異步操作)。