2014-05-07 100 views
0

我有以下代碼從HTTPServer下載一組文件。它給出了第一對文件的響應,稍後會陷入獲得響應。我可以從我創建的日誌文件中驗證這一點。在日誌文件中,它會寫入「在webresponse之前」,但從未達到第三個文件的「webresponse」之後。我已經在使用web響應。這裏有什麼可愛的?HTTPResponse掛起多個請求

  Logger.WriteToLog("url = " +url); 
      // Create a request to the file we are downloading 
      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 
      webRequest.Timeout = 120000; 
      webRequest.ReadWriteTimeout = 300000; 

      // Set default authentication for retrieving the file 
      //webRequest.Credentials = new NetworkCredential(GlobalVariables.username, GlobalVariables.password); 
      webRequest.UseDefaultCredentials = true; 

      // Retrieve the response from the server 
      Logger.WriteToLog("Before webresponse"); 
      using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) 
      { 
       Logger.WriteToLog("After webresponse"); 

       // Ask the server for the file size and store it 
       //Int64 fileSize = webResponse.ContentLength; 

       // Open the URL for download 
       using (Stream strResponse = webResponse.GetResponseStream()) 
       { 
        // Create a new file stream where we will be saving the data (local drive) 
        strLocal = File.Create(destFilePath); 

        // Loop through the buffer until the buffer is empty 
        while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) 
        { 
         if (isPaused) 
          waitRun_m.WaitOne(); 

         if (isCanceled) 
          break; 

         strLocal.Write(downBuffer, 0, bytesSize); 
         // Invoke the method that updates the form's label and progress bar 
         UpdateProgessCallback(mediaName, bytesSize); 
        }; 

        strResponse.Close(); 
       } 

      } 
+0

destFilePath在ecach響應上應該是不同的,或者你可能有一些文件鎖定問題。 –

+0

是的。每個響應的destFilePath都不相同。 –

+0

寫入後關閉文件。 strLocal.Close();你正在創建Allways文件,或許會更好地創建文件,只有當你有一個響應(即時只是試圖改善代碼,答案可能有點不同)。 –

回答

0

我嘗試了ServicePoint類的方法,現在工作正常。我所做的是在爲webrequest添加readwritetimeout之後,我使用以下語句爲連接組指定了名稱:

webRequest.ConnectionGroupName = some_name;

和關閉連接時所做的:

webRequest.ServicePoint.CloseConnectionGroup(some_name);