簡體   English   中英

循環中的 WebClient 工作一次,然后超時

[英]WebClient in loop works once, then times out

我從 web 源下載一些文件的代碼將從服務器檢索文件名,然后開始下載。 然而,一旦它獲取了隊列中第二個文件名,它就會停止下載並最終超時。 我在這里錯過了什么? 任何建議表示贊賞。

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string[] s = (string[])e.Argument;

        for (int x = 0; x < s.Length; x++) {

            using (WebClient client = new WebClient())
            {
               
                client.OpenRead(s[x]);

                string header_contentDisposition = client.ResponseHeaders["content-disposition"];
                string filename = new ContentDisposition(header_contentDisposition).FileName;

                

                string filedownload = AppDomain.CurrentDomain.BaseDirectory + filename;
                var url = new Uri(s[x]);

                client.DownloadFileAsync(url, filedownload);
                client.Dispose();


                /* HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                 {

                     var wresp = (HttpWebResponse)request.GetResponse();

                     using (Stream file = File.OpenWrite(filename))
                     {
                         wresp.GetResponseStream().CopyTo(file);

                     }
                 }
                */


                //client.DownloadFileAsync(url, filedownload);



            }
        }
    }

在多次更改我的下載代碼並且每次都有類似的結果后,我發現添加了以下內容:

System.Net.ServicePointManager.DefaultConnectionLimit = 10;

我的表格解決了這個問題。 不要問我為什么會這樣,我想要一個解釋。

查看此解釋https://learn.microsoft.com/de-de/archive/blogs/jpsanders/understanding-maxservicepointidletime-and-defaultconnectionlimit

如果注釋代碼是破壞它的代碼的一部分,請嘗試使用 .Close() 關閉您的請求。 它們可能會被處理掉,因為您在使用塊時使用了它們,但它仍然在 ServicePoint object 中保持連接處於活動狀態/打開狀態,並且由於 DefaultConnectionLimit 默認設置為 2,因此您的 ServicePoint 已經被阻塞。

在我的項目中,我首先使用 WebRequest/Response 獲取要顯示給用戶的文件大小,然后下載文件,這只工作了一次。 關閉 Response 對象后,它開始正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM