[英]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;
我的表格解决了这个问题。 不要问我为什么会这样,我想要一个解释。
如果注释代码是破坏它的代码的一部分,请尝试使用 .Close() 关闭您的请求。 它们可能会被处理掉,因为您在使用块时使用了它们,但它仍然在 ServicePoint object 中保持连接处于活动状态/打开状态,并且由于 DefaultConnectionLimit 默认设置为 2,因此您的 ServicePoint 已经被阻塞。
在我的项目中,我首先使用 WebRequest/Response 获取要显示给用户的文件大小,然后下载文件,这只工作了一次。 关闭 Response 对象后,它开始正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.