简体   繁体   中英

WebClient in loop works once, then times out

My code to download a handful of files from a web source will retrieve the files name from the server and then begin the download. However once it grabs the filename for the second in the queue, it stops downloading and eventually times out. What am I missing here? Any advice appreciated.

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



            }
        }
    }

After changing my download code several times and having similar results each time, I found adding the following:

System.Net.ServicePointManager.DefaultConnectionLimit = 10;

to my form fixed the issue. Don't ask me why that works, I'd love an explanation.

Check this explanation out https://learn.microsoft.com/de-de/archive/blogs/jpsanders/understanding-maxservicepointidletime-and-defaultconnectionlimit

If the commented code is part of the code which breaks it then try closing your requests using.Close(). They might get disposed of since you have them in using blocks, but it still keeps the connection active/open in the ServicePoint object and since DefaultConnectionLimit is set to 2 by default, your ServicePoint is already clogged.

In my project I was first getting the size of the file to display to the user using WebRequest/Response and then download the file, and that worked only once. Upon closing the Response objects, it started working properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM